repo
string
commit
string
message
string
diff
string
ekmett/tagged
15fcfe90c779efea951ecf4d451d709aed5f7d32
Finalize version 0.8.6.1
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index c578e63..3c415bc 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,93 +1,93 @@ -0.8.6.1 [20yy.mm.dd] ------------------- +0.8.6.1 [2020.12.28] +-------------------- * Mark all modules as explicitly Safe or Trustworthy. 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support
ekmett/tagged
8618af2c6b7efa9f21fb157114c2a52cd841b17d
Migrate from Travis CI to GitHub Actions
diff --git a/.github/workflows/haskell-ci.yml b/.github/workflows/haskell-ci.yml new file mode 100644 index 0000000..1b54975 --- /dev/null +++ b/.github/workflows/haskell-ci.yml @@ -0,0 +1,198 @@ +# This GitHub workflow config has been generated by a script via +# +# haskell-ci 'github' '--config=cabal.haskell-ci' 'cabal.project' +# +# To regenerate the script (for example after adjusting tested-with) run +# +# haskell-ci regenerate +# +# For more information, see https://github.com/haskell-CI/haskell-ci +# +# version: 0.11.20201227 +# +# REGENDATA ("0.11.20201227",["github","--config=cabal.haskell-ci","cabal.project"]) +# +name: Haskell-CI +on: + - push + - pull_request +jobs: + irc: + name: Haskell-CI (IRC notification) + runs-on: ubuntu-18.04 + needs: + - linux + if: ${{ always() && (github.repository == 'ekmett/tagged') }} + strategy: + fail-fast: false + steps: + - name: IRC success notification (irc.freenode.org#haskell-lens) + uses: Gottox/[email protected] + if: needs.linux.result == 'success' + with: + channel: "#haskell-lens" + message: "\x0313tagged\x03/\x0306${{ github.ref }}\x03 \x0314${{ github.sha }}\x03 https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} The build succeeded." + nickname: github-actions + server: irc.freenode.org + - name: IRC failure notification (irc.freenode.org#haskell-lens) + uses: Gottox/[email protected] + if: needs.linux.result != 'success' + with: + channel: "#haskell-lens" + message: "\x0313tagged\x03/\x0306${{ github.ref }}\x03 \x0314${{ github.sha }}\x03 https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} The build failed." + nickname: github-actions + server: irc.freenode.org + linux: + name: Haskell-CI Linux - GHC ${{ matrix.ghc }} + runs-on: ubuntu-18.04 + container: + image: buildpack-deps:bionic + continue-on-error: ${{ matrix.allow-failure }} + strategy: + matrix: + include: + - ghc: 8.10.1 + allow-failure: false + - ghc: 8.8.3 + allow-failure: false + - ghc: 8.6.5 + allow-failure: false + - ghc: 8.4.4 + allow-failure: false + - ghc: 8.2.2 + allow-failure: false + - ghc: 8.0.2 + allow-failure: false + - ghc: 7.10.3 + allow-failure: false + - ghc: 7.8.4 + allow-failure: false + - ghc: 7.6.3 + allow-failure: false + - ghc: 7.4.2 + allow-failure: false + - ghc: 7.2.2 + allow-failure: true + - ghc: 7.0.4 + allow-failure: true + fail-fast: false + steps: + - name: apt + run: | + apt-get update + apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common + apt-add-repository -y 'ppa:hvr/ghc' + apt-get update + apt-get install -y ghc-$GHC_VERSION cabal-install-3.2 + env: + GHC_VERSION: ${{ matrix.ghc }} + - name: Set PATH and environment variables + run: | + echo "$HOME/.cabal/bin" >> $GITHUB_PATH + echo "LANG=C.UTF-8" >> $GITHUB_ENV + echo "CABAL_DIR=$HOME/.cabal" >> $GITHUB_ENV + echo "CABAL_CONFIG=$HOME/.cabal/config" >> $GITHUB_ENV + HC=/opt/ghc/$GHC_VERSION/bin/ghc + echo "HC=$HC" >> $GITHUB_ENV + echo "HCPKG=/opt/ghc/$GHC_VERSION/bin/ghc-pkg" >> $GITHUB_ENV + echo "HADDOCK=/opt/ghc/$GHC_VERSION/bin/haddock" >> $GITHUB_ENV + echo "CABAL=/opt/cabal/3.2/bin/cabal -vnormal+nowrap" >> $GITHUB_ENV + HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))') + echo "HCNUMVER=$HCNUMVER" >> $GITHUB_ENV + echo "ARG_TESTS=--enable-tests" >> $GITHUB_ENV + echo "ARG_BENCH=--enable-benchmarks" >> $GITHUB_ENV + echo "ARG_COMPILER=--ghc --with-compiler=/opt/ghc/$GHC_VERSION/bin/ghc" >> $GITHUB_ENV + echo "GHCJSARITH=0" >> $GITHUB_ENV + env: + GHC_VERSION: ${{ matrix.ghc }} + - name: env + run: | + env + - name: write cabal config + run: | + mkdir -p $CABAL_DIR + cat >> $CABAL_CONFIG <<EOF + remote-build-reporting: anonymous + write-ghc-environment-files: never + remote-repo-cache: $CABAL_DIR/packages + logs-dir: $CABAL_DIR/logs + world-file: $CABAL_DIR/world + extra-prog-path: $CABAL_DIR/bin + symlink-bindir: $CABAL_DIR/bin + installdir: $CABAL_DIR/bin + build-summary: $CABAL_DIR/logs/build.log + store-dir: $CABAL_DIR/store + install-dirs user + prefix: $CABAL_DIR + repository hackage.haskell.org + url: http://hackage.haskell.org/ + EOF + cat $CABAL_CONFIG + - name: versions + run: | + $HC --version || true + $HC --print-project-git-commit-id || true + $CABAL --version || true + - name: update cabal index + run: | + $CABAL v2-update -v + - name: install cabal-plan + run: | + mkdir -p $HOME/.cabal/bin + curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.6.2.0/cabal-plan-0.6.2.0-x86_64-linux.xz > cabal-plan.xz + echo 'de73600b1836d3f55e32d80385acc055fd97f60eaa0ab68a755302685f5d81bc cabal-plan.xz' | sha256sum -c - + xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan + rm -f cabal-plan.xz + chmod a+x $HOME/.cabal/bin/cabal-plan + cabal-plan --version + - name: checkout + uses: actions/checkout@v2 + with: + path: source + - name: sdist + run: | + mkdir -p sdist + cd source || false + $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist + - name: unpack + run: | + mkdir -p unpacked + find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \; + - name: generate cabal.project + run: | + PKGDIR_tagged="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" + echo "PKGDIR_tagged=${PKGDIR_tagged}" >> $GITHUB_ENV + touch cabal.project + touch cabal.project.local + echo "packages: ${PKGDIR_tagged}" >> cabal.project + if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo "package tagged" >> cabal.project ; fi + if [ $((HCNUMVER >= 80200)) -ne 0 ] ; then echo " ghc-options: -Werror=missing-methods" >> cabal.project ; fi + cat >> cabal.project <<EOF + EOF + $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(tagged)$/; }' >> cabal.project.local + cat cabal.project + cat cabal.project.local + - name: dump install plan + run: | + $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all + cabal-plan + - name: cache + uses: actions/cache@v2 + with: + key: ${{ runner.os }}-${{ matrix.ghc }}-${{ github.sha }} + path: ~/.cabal/store + restore-keys: ${{ runner.os }}-${{ matrix.ghc }}- + - name: install dependencies + run: | + $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all + $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all + - name: build + run: | + $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always + - name: cabal check + run: | + cd ${PKGDIR_tagged} || false + ${CABAL} -vnormal check + - name: haddock + run: | + $CABAL v2-haddock $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6fb08d2..0000000 --- a/.travis.yml +++ /dev/null @@ -1,171 +0,0 @@ -# This Travis job script has been generated by a script via -# -# haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' -# -# To regenerate the script (for example after adjusting tested-with) run -# -# haskell-ci regenerate -# -# For more information, see https://github.com/haskell-CI/haskell-ci -# -# version: 0.10 -# -version: ~> 1.0 -language: c -os: linux -dist: xenial -git: - # whether to recursively clone submodules - submodules: false -notifications: - irc: - channels: - - irc.freenode.org#haskell-lens - skip_join: true - template: - - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" -cache: - directories: - - $HOME/.cabal/packages - - $HOME/.cabal/store - - $HOME/.hlint -before_cache: - - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log - # remove files that are regenerated by 'cabal update' - - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.* - - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json - - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache - - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar - - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx - - rm -rfv $CABALHOME/packages/head.hackage -jobs: - include: - - compiler: ghc-8.10.1 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.10.1","cabal-install-3.2"]}} - os: linux - - compiler: ghc-8.8.3 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.8.3","cabal-install-3.2"]}} - os: linux - - compiler: ghc-8.6.5 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.6.5","cabal-install-3.2"]}} - os: linux - - compiler: ghc-8.4.4 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.4.4","cabal-install-3.2"]}} - os: linux - - compiler: ghc-8.2.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.2.2","cabal-install-3.2"]}} - os: linux - - compiler: ghc-8.0.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.0.2","cabal-install-3.2"]}} - os: linux - - compiler: ghc-7.10.3 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.10.3","cabal-install-3.2"]}} - os: linux - - compiler: ghc-7.8.4 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.8.4","cabal-install-3.2"]}} - os: linux - - compiler: ghc-7.6.3 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.6.3","cabal-install-3.2"]}} - os: linux - - compiler: ghc-7.4.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.4.2","cabal-install-3.2"]}} - os: linux - - compiler: ghc-7.2.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.2.2","cabal-install-3.2"]}} - os: linux - - compiler: ghc-7.0.4 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.0.4","cabal-install-3.2"]}} - os: linux - allow_failures: - - compiler: ghc-7.0.4 - - compiler: ghc-7.2.2 -before_install: - - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//') - - WITHCOMPILER="-w $HC" - - HADDOCK=$(echo "/opt/$CC/bin/haddock" | sed 's/-/\//') - - HCPKG="$HC-pkg" - - unset CC - - CABAL=/opt/ghc/bin/cabal - - CABALHOME=$HOME/.cabal - - export PATH="$CABALHOME/bin:$PATH" - - TOP=$(pwd) - - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')" - - echo $HCNUMVER - - CABAL="$CABAL -vnormal+nowrap" - - set -o pipefail - - TEST=--enable-tests - - BENCH=--enable-benchmarks - - HEADHACKAGE=false - - rm -f $CABALHOME/config - - | - echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config - echo "remote-build-reporting: anonymous" >> $CABALHOME/config - echo "write-ghc-environment-files: always" >> $CABALHOME/config - echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config - echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config - echo "world-file: $CABALHOME/world" >> $CABALHOME/config - echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config - echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config - echo "installdir: $CABALHOME/bin" >> $CABALHOME/config - echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config - echo "store-dir: $CABALHOME/store" >> $CABALHOME/config - echo "install-dirs user" >> $CABALHOME/config - echo " prefix: $CABALHOME" >> $CABALHOME/config - echo "repository hackage.haskell.org" >> $CABALHOME/config - echo " url: http://hackage.haskell.org/" >> $CABALHOME/config -install: - - ${CABAL} --version - - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - - | - echo "program-default-options" >> $CABALHOME/config - echo " ghc-options: $GHCJOBS +RTS -M6G -RTS" >> $CABALHOME/config - - cat $CABALHOME/config - - rm -fv cabal.project cabal.project.local cabal.project.freeze - - travis_retry ${CABAL} v2-update -v - # Generate cabal.project - - rm -rf cabal.project cabal.project.local cabal.project.freeze - - touch cabal.project - - | - echo "packages: ." >> cabal.project - - if [ $HCNUMVER -ge 80200 ] ; then echo 'package tagged' >> cabal.project ; fi - - "if [ $HCNUMVER -ge 80200 ] ; then echo ' ghc-options: -Werror=missing-methods' >> cabal.project ; fi" - - | - - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - - cat cabal.project || true - - cat cabal.project.local || true - - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} - - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" - - rm cabal.project.freeze - - travis_wait 40 ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all -script: - - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) - # Packaging... - - ${CABAL} v2-sdist all - # Unpacking... - - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - - cd ${DISTDIR} || false - - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \; - - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \; - - PKGDIR_tagged="$(find . -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" - # Generate cabal.project - - rm -rf cabal.project cabal.project.local cabal.project.freeze - - touch cabal.project - - | - echo "packages: ${PKGDIR_tagged}" >> cabal.project - - if [ $HCNUMVER -ge 80200 ] ; then echo 'package tagged' >> cabal.project ; fi - - "if [ $HCNUMVER -ge 80200 ] ; then echo ' ghc-options: -Werror=missing-methods' >> cabal.project ; fi" - - | - - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - - cat cabal.project || true - - cat cabal.project.local || true - # Building with tests and benchmarks... - # build & run tests, build benchmarks - - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all - # cabal check... - - (cd ${PKGDIR_tagged} && ${CABAL} -vnormal check) - # haddock... - - ${CABAL} v2-haddock $WITHCOMPILER --with-haddock $HADDOCK ${TEST} ${BENCH} all - -# REGENDATA ("0.10",["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"]) -# EOF diff --git a/README.markdown b/README.markdown index f7e55d8..573b31d 100644 --- a/README.markdown +++ b/README.markdown @@ -1,6 +1,6 @@ tagged ====== -[![Hackage](https://img.shields.io/hackage/v/tagged.svg)](https://hackage.haskell.org/package/tagged) [![Build Status](https://secure.travis-ci.org/ekmett/tagged.png?branch=master)](http://travis-ci.org/ekmett/tagged) +[![Hackage](https://img.shields.io/hackage/v/tagged.svg)](https://hackage.haskell.org/package/tagged) [![Build Status](https://github.com/ekmett/tagged/workflows/Haskell-CI/badge.svg)](https://github.com/ekmett/tagged/actions?query=workflow%3AHaskell-CI) Values carrying an extra [phantom type](https://wiki.haskell.org/Phantom_type) tag. diff --git a/cabal.haskell-ci b/cabal.haskell-ci index 85dd80c..6331f0b 100644 --- a/cabal.haskell-ci +++ b/cabal.haskell-ci @@ -1,4 +1,5 @@ no-tests-no-benchmarks: False unconstrained: False allow-failures: <7.3 irc-channels: irc.freenode.org#haskell-lens +irc-if-in-origin-repo: True diff --git a/tagged.cabal b/tagged.cabal index 1521a80..e392151 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,89 +1,89 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 -extra-source-files: .hlint.yaml .travis.yml CHANGELOG.markdown README.markdown +extra-source-files: .hlint.yaml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.3 , GHC == 8.10.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if impl(ghc >= 9.0) -- these flags may abort compilation with GHC-8.10 -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.18 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
7f079d50feec35059d7a040588b576c9561e4ed2
Use -Winferred-safe-imports with GHC-9.0+ (#52)
diff --git a/tagged.cabal b/tagged.cabal index 616e23a..1521a80 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,87 +1,89 @@ name: tagged version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml .travis.yml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.3 , GHC == 8.10.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged - if impl(ghc >= 8.10) + if impl(ghc >= 9.0) + -- these flags may abort compilation with GHC-8.10 + -- https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3295 ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.18 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
896a49663b4c3d4af7906351381b1a20150eccce
Make Tagged explicitly safe (#51)
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 0d85056..c578e63 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,89 +1,93 @@ +0.8.6.1 [20yy.mm.dd] +------------------ +* Mark all modules as explicitly Safe or Trustworthy. + 0.8.6 [2018.07.02] ------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/src/Data/Proxy/TH.hs b/src/Data/Proxy/TH.hs index f571ea3..6a83334 100644 --- a/src/Data/Proxy/TH.hs +++ b/src/Data/Proxy/TH.hs @@ -1,96 +1,102 @@ {-# LANGUAGE CPP #-} #ifndef MIN_VERSION_template_haskell #define MIN_VERSION_template_haskell(x,y,z) 1 #endif +-- template-haskell is only safe since GHC-8.2 +#if __GLASGOW_HASKELL__ >= 802 +{-# LANGUAGE Safe #-} +#elif __GLASGOW_HASKELL__ >= 702 +{-# LANGUAGE Trustworthy #-} +#endif module Data.Proxy.TH ( pr #if MIN_VERSION_template_haskell(2,8,0) , pr1 #endif ) where import Data.Char #if __GLASGOW_HASKELL__ < 710 import Data.Functor #endif #if __GLASGOW_HASKELL__ < 707 import Data.Version (showVersion) import Paths_tagged #endif import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax proxy_d, proxy_tc :: Name #if __GLASGOW_HASKELL__ >= 707 proxy_d = mkNameG_d "base" "Data.Proxy" "Proxy" proxy_tc = mkNameG_tc "base" "Data.Proxy" "Proxy" #else proxy_d = mkNameG_d taggedPackageKey "Data.Proxy" "Proxy" proxy_tc = mkNameG_tc taggedPackageKey "Data.Proxy" "Proxy" -- note: On 7.10+ this would use CURRENT_PACKAGE_KEY if we still housed the key. taggedPackageKey :: String taggedPackageKey = "tagged-" ++ showVersion version #endif proxyTypeQ :: TypeQ -> TypeQ proxyTypeQ t = appT (conT proxy_tc) t proxyExpQ :: TypeQ -> ExpQ proxyExpQ t = sigE (conE proxy_d) (proxyTypeQ t) proxyPatQ :: TypeQ -> PatQ proxyPatQ t = sigP (conP proxy_d []) (proxyTypeQ t) -- | A proxy value quasiquoter. @[pr|T|]@ will splice an expression -- @Proxy::Proxy T@, while @[pr|A,B,C|]@ will splice in a value of -- @Proxy :: Proxy [A,B,C]@. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr :: QuasiQuoter pr = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where mkProxy :: (TypeQ -> r) -> String -> r mkProxy p s = case ts of [h@(t:_)] | isUpper t -> p $ head <$> cons | otherwise -> p $ varT $ mkName h #if MIN_VERSION_template_haskell(2,8,0) _ -> p $ mkList <$> cons #endif where ts = map strip $ splitOn ',' s cons = mapM (conT . mkName) ts #if MIN_VERSION_template_haskell(2,8,0) mkList = foldr (AppT . AppT PromotedConsT) PromotedNilT #endif #if MIN_VERSION_template_haskell(2,8,0) -- | Like 'pr', but takes a single type, which is used to produce a -- 'Proxy' for a single-element list containing only that type. This -- is useful for passing a single type to a function that wants a list -- of types. -- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. pr1 :: QuasiQuoter pr1 = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where sing x = AppT (AppT PromotedConsT x) PromotedNilT mkProxy p s = case s of t:_ | isUpper t -> p (fmap sing (conT $ mkName s)) | otherwise -> p (fmap sing (varT $ mkName s)) _ -> error "Empty string passed to pr1" #endif -- | Split on a delimiter. splitOn :: Eq a => a -> [a] -> [[a]] splitOn d = go where go [] = [] go xs = case t of [] -> [h] (_:t') -> h : go t' where (h,t) = break (== d) xs -- | Remove white space from both ends of a 'String'. strip :: String -> String strip = takeWhile (not . isSpace) . dropWhile isSpace diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs index edd247c..af3278d 100644 --- a/src/Data/Tagged.hs +++ b/src/Data/Tagged.hs @@ -1,488 +1,491 @@ {-# LANGUAGE CPP #-} #ifdef LANGUAGE_DeriveDataTypeable {-# LANGUAGE DeriveDataTypeable #-} #endif #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE PolyKinds #-} #endif #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE DeriveGeneric #-} -#if __GLASGOW_HASKELL__ < 710 -{-# LANGUAGE Trustworthy #-} #endif +-- manual generics instances are not safe +#if __GLASGOW_HASKELL__ >= 707 +{-# LANGUAGE Safe #-} +#elif __GLASGOW_HASKELL__ >= 702 +{-# LANGUAGE Trustworthy #-} #endif {-# OPTIONS_GHC -fno-warn-deprecations #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Tagged -- Copyright : 2009-2015 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Tagged ( -- * Tagged values Tagged(..) , retag , untag , tagSelf , untagSelf , asTaggedTypeOf , witness -- * Conversion , proxy , unproxy , tagWith -- * Proxy methods GHC dropped , reproxy ) where #if MIN_VERSION_base(4,8,0) import Control.Applicative (liftA2) #else import Control.Applicative ((<$>), liftA2, Applicative(..)) import Data.Traversable (Traversable(..)) import Data.Monoid #endif import Data.Bits import Data.Foldable (Foldable(..)) #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif #ifdef MIN_VERSION_transformers import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) # if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) , Eq2(..), Ord2(..), Read2(..), Show2(..) # endif ) #endif import Control.Monad (liftM) #if MIN_VERSION_base(4,8,0) import Data.Bifunctor #endif #if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) #endif #ifdef __GLASGOW_HASKELL__ import Data.Data #endif import Data.Ix (Ix(..)) #if __GLASGOW_HASKELL__ < 707 import Data.Proxy #endif #if MIN_VERSION_base(4,9,0) import Data.Semigroup (Semigroup(..)) #endif import Data.String (IsString(..)) import Foreign.Ptr (castPtr) import Foreign.Storable (Storable(..)) #if __GLASGOW_HASKELL__ >= 702 import GHC.Generics (Generic) #if __GLASGOW_HASKELL__ >= 706 import GHC.Generics (Generic1) #endif #endif -- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. -- This can be used in place of the more traditional but less safe idiom of -- passing in an undefined value with the type, because unlike an @(s -> b)@, -- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the extra -- argument, because the newtype is \"free\" -- -- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore -- there is an extra @k@ showing in the instance haddocks that may cause confusion. newtype Tagged s b = Tagged { unTagged :: b } deriving ( Eq, Ord, Ix, Bounded #if __GLASGOW_HASKELL__ >= 702 , Generic #if __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #endif #if __GLASGOW_HASKELL__ >= 707 , Typeable #endif ) #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 707 instance Typeable2 Tagged where typeOf2 _ = mkTyConApp taggedTyCon [] taggedTyCon :: TyCon #if __GLASGOW_HASKELL__ < 704 taggedTyCon = mkTyCon "Data.Tagged.Tagged" #else taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged" #endif #endif instance (Data s, Data b) => Data (Tagged s b) where gfoldl f z (Tagged b) = z Tagged `f` b toConstr _ = taggedConstr gunfold k z c = case constrIndex c of 1 -> k (z Tagged) _ -> error "gunfold" dataTypeOf _ = taggedDataType dataCast1 f = gcast1 f dataCast2 f = gcast2 f taggedConstr :: Constr taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix {-# INLINE taggedConstr #-} taggedDataType :: DataType taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] {-# INLINE taggedDataType #-} #endif instance Show b => Show (Tagged s b) where showsPrec n (Tagged b) = showParen (n > 10) $ showString "Tagged " . showsPrec 11 b instance Read b => Read (Tagged s b) where readsPrec d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] #if MIN_VERSION_base(4,9,0) instance Semigroup a => Semigroup (Tagged s a) where Tagged a <> Tagged b = Tagged (a <> b) stimes n (Tagged a) = Tagged (stimes n a) instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where mempty = Tagged mempty mappend = (<>) #else instance Monoid a => Monoid (Tagged s a) where mempty = Tagged mempty mappend (Tagged a) (Tagged b) = Tagged (mappend a b) #endif instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} #if MIN_VERSION_base(4,8,0) -- this instance is provided by the bifunctors package for GHC<7.9 instance Bifunctor Tagged where bimap _ g (Tagged b) = Tagged (g b) {-# INLINE bimap #-} #endif #if MIN_VERSION_base(4,10,0) -- these instances are provided by the bifunctors package for GHC<8.1 instance Bifoldable Tagged where bifoldMap _ g (Tagged b) = g b {-# INLINE bifoldMap #-} instance Bitraversable Tagged where bitraverse _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse #-} #endif #ifdef MIN_VERSION_deepseq instance NFData b => NFData (Tagged s b) where rnf (Tagged b) = rnf b #endif #ifdef MIN_VERSION_transformers # if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) instance Eq1 (Tagged s) where eq1 = (==) instance Ord1 (Tagged s) where compare1 = compare instance Read1 (Tagged s) where readsPrec1 = readsPrec instance Show1 (Tagged s) where showsPrec1 = showsPrec # else instance Eq1 (Tagged s) where liftEq eq (Tagged a) (Tagged b) = eq a b instance Ord1 (Tagged s) where liftCompare cmp (Tagged a) (Tagged b) = cmp a b instance Read1 (Tagged s) where liftReadsPrec rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show1 (Tagged s) where liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b instance Eq2 Tagged where liftEq2 _ eq (Tagged a) (Tagged b) = eq a b instance Ord2 Tagged where liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b instance Read2 Tagged where liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show2 Tagged where liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b # endif #endif instance Applicative (Tagged s) where pure = Tagged {-# INLINE pure #-} Tagged f <*> Tagged x = Tagged (f x) {-# INLINE (<*>) #-} _ *> n = n {-# INLINE (*>) #-} instance Monad (Tagged s) where return = pure {-# INLINE return #-} Tagged m >>= k = k m {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Foldable (Tagged s) where foldMap f (Tagged x) = f x {-# INLINE foldMap #-} fold (Tagged x) = x {-# INLINE fold #-} foldr f z (Tagged x) = f x z {-# INLINE foldr #-} foldl f z (Tagged x) = f z x {-# INLINE foldl #-} foldl1 _ (Tagged x) = x {-# INLINE foldl1 #-} foldr1 _ (Tagged x) = x {-# INLINE foldr1 #-} instance Traversable (Tagged s) where traverse f (Tagged x) = Tagged <$> f x {-# INLINE traverse #-} sequenceA (Tagged x) = Tagged <$> x {-# INLINE sequenceA #-} mapM f (Tagged x) = liftM Tagged (f x) {-# INLINE mapM #-} sequence (Tagged x) = liftM Tagged x {-# INLINE sequence #-} instance Enum a => Enum (Tagged s a) where succ = fmap succ pred = fmap pred toEnum = Tagged . toEnum fromEnum (Tagged x) = fromEnum x enumFrom (Tagged x) = map Tagged (enumFrom x) enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = map Tagged (enumFromThenTo x y z) instance Num a => Num (Tagged s a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = Tagged . fromInteger instance Real a => Real (Tagged s a) where toRational (Tagged x) = toRational x instance Integral a => Integral (Tagged s a) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = quotRem x y divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = divMod x y toInteger (Tagged x) = toInteger x instance Fractional a => Fractional (Tagged s a) where (/) = liftA2 (/) recip = fmap recip fromRational = Tagged . fromRational instance Floating a => Floating (Tagged s a) where pi = Tagged pi exp = fmap exp log = fmap log sqrt = fmap sqrt sin = fmap sin cos = fmap cos tan = fmap tan asin = fmap asin acos = fmap acos atan = fmap atan sinh = fmap sinh cosh = fmap cosh tanh = fmap tanh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh (**) = liftA2 (**) logBase = liftA2 logBase instance RealFrac a => RealFrac (Tagged s a) where properFraction (Tagged x) = (a, Tagged b) where (a, b) = properFraction x truncate (Tagged x) = truncate x round (Tagged x) = round x ceiling (Tagged x) = ceiling x floor (Tagged x) = floor x instance RealFloat a => RealFloat (Tagged s a) where floatRadix (Tagged x) = floatRadix x floatDigits (Tagged x) = floatDigits x floatRange (Tagged x) = floatRange x decodeFloat (Tagged x) = decodeFloat x encodeFloat m n = Tagged (encodeFloat m n) exponent (Tagged x) = exponent x significand = fmap significand scaleFloat n = fmap (scaleFloat n) isNaN (Tagged x) = isNaN x isInfinite (Tagged x) = isInfinite x isDenormalized (Tagged x) = isDenormalized x isNegativeZero (Tagged x) = isNegativeZero x isIEEE (Tagged x) = isIEEE x atan2 = liftA2 atan2 instance Bits a => Bits (Tagged s a) where Tagged a .&. Tagged b = Tagged (a .&. b) Tagged a .|. Tagged b = Tagged (a .|. b) xor (Tagged a) (Tagged b) = Tagged (xor a b) complement (Tagged a) = Tagged (complement a) shift (Tagged a) i = Tagged (shift a i) shiftL (Tagged a) i = Tagged (shiftL a i) shiftR (Tagged a) i = Tagged (shiftR a i) rotate (Tagged a) i = Tagged (rotate a i) rotateL (Tagged a) i = Tagged (rotateL a i) rotateR (Tagged a) i = Tagged (rotateR a i) bit i = Tagged (bit i) setBit (Tagged a) i = Tagged (setBit a i) clearBit (Tagged a) i = Tagged (clearBit a i) complementBit (Tagged a) i = Tagged (complementBit a i) testBit (Tagged a) i = testBit a i isSigned (Tagged a) = isSigned a bitSize (Tagged a) = bitSize a -- deprecated, but still required :( #if MIN_VERSION_base(4,5,0) unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) popCount (Tagged a) = popCount a #endif #if MIN_VERSION_base(4,7,0) bitSizeMaybe (Tagged a) = bitSizeMaybe a zeroBits = Tagged zeroBits #endif #if MIN_VERSION_base(4,7,0) instance FiniteBits a => FiniteBits (Tagged s a) where finiteBitSize (Tagged a) = finiteBitSize a # if MIN_VERSION_base(4,8,0) countLeadingZeros (Tagged a) = countLeadingZeros a countTrailingZeros (Tagged a) = countTrailingZeros a # endif #endif instance IsString a => IsString (Tagged s a) where fromString = Tagged . fromString instance Storable a => Storable (Tagged s a) where sizeOf t = sizeOf a where Tagged a = Tagged undefined `asTypeOf` t alignment t = alignment a where Tagged a = Tagged undefined `asTypeOf` t peek ptr = Tagged <$> peek (castPtr ptr) poke ptr (Tagged a) = poke (castPtr ptr) a peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a -- | Some times you need to change the tag you have lying around. -- Idiomatic usage is to make a new combinator for the relationship between the -- tags that you want to enforce, and define that combinator using 'retag'. -- -- @ -- data Succ n -- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a -- retagSucc = 'retag' -- @ retag :: Tagged s b -> Tagged t b retag = Tagged . unTagged {-# INLINE retag #-} -- | Alias for 'unTagged' untag :: Tagged s b -> b untag = unTagged -- | Tag a value with its own type. tagSelf :: a -> Tagged a a tagSelf = Tagged {-# INLINE tagSelf #-} -- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. asTaggedTypeOf :: s -> tagged s b -> s asTaggedTypeOf = const {-# INLINE asTaggedTypeOf #-} witness :: Tagged a b -> a -> b witness (Tagged b) _ = b {-# INLINE witness #-} -- | 'untagSelf' is a type-restricted version of 'untag'. untagSelf :: Tagged a a -> a untagSelf (Tagged x) = x {-# INLINE untagSelf #-} -- | Convert from a 'Tagged' representation to a representation -- based on a 'Proxy'. proxy :: Tagged s a -> proxy s -> a proxy (Tagged x) _ = x {-# INLINE proxy #-} -- | Convert from a representation based on a 'Proxy' to a 'Tagged' -- representation. unproxy :: (Proxy s -> a) -> Tagged s a unproxy f = Tagged (f Proxy) {-# INLINE unproxy #-} -- | Another way to convert a proxy to a tag. tagWith :: proxy s -> a -> Tagged s a tagWith _ = Tagged {-# INLINE tagWith #-} -- | Some times you need to change the proxy you have lying around. -- Idiomatic usage is to make a new combinator for the relationship -- between the proxies that you want to enforce, and define that -- combinator using 'reproxy'. -- -- @ -- data Succ n -- reproxySucc :: proxy n -> 'Proxy' (Succ n) -- reproxySucc = 'reproxy' -- @ reproxy :: proxy a -> Proxy b reproxy _ = Proxy diff --git a/tagged.cabal b/tagged.cabal index a6583e3..616e23a 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,84 +1,87 @@ name: tagged -version: 0.8.6 +version: 0.8.6.1 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml .travis.yml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.3 , GHC == 8.10.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged + if impl(ghc >= 8.10) + ghc-options: -Winferred-safe-imports -Wmissing-safe-haskell-mode + if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.18 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
5cc59cc2e994549ad24a1a4a1840d8b132ff3a59
Relax template-haskell upper bound (#50)
diff --git a/tagged.cabal b/tagged.cabal index 75fbb04..a6583e3 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,84 +1,84 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml .travis.yml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.3 , GHC == 8.10.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.17 + build-depends: template-haskell >= 2.8 && < 2.18 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
8aec7fc61dcd1ea60ea7ec9c63b66e67027f110e
Regenerate .travis.yml
diff --git a/.travis.yml b/.travis.yml index 879c5e7..6fb08d2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,206 +1,171 @@ # This Travis job script has been generated by a script via # # haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' # +# To regenerate the script (for example after adjusting tested-with) run +# +# haskell-ci regenerate +# # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.9.20191126 +# version: 0.10 # version: ~> 1.0 language: c os: linux dist: xenial git: # whether to recursively clone submodules submodules: false notifications: irc: channels: - irc.freenode.org#haskell-lens skip_join: true template: - - "\"\\x0313tagged\\x03/\\x0306%{branch}\\x03 \\x0314%{commit}\\x03 %{build_url} %{message}\"" + - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store - $HOME/.hlint before_cache: - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.* - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $CABALHOME/packages/head.hackage jobs: include: - compiler: ghc-8.10.1 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.10.1","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.10.1","cabal-install-3.2"]}} os: linux - - compiler: ghc-8.8.1 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.8.1","cabal-install-3.0"]}} + - compiler: ghc-8.8.3 + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.8.3","cabal-install-3.2"]}} os: linux - compiler: ghc-8.6.5 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.6.5","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.6.5","cabal-install-3.2"]}} os: linux - compiler: ghc-8.4.4 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.4.4","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.4.4","cabal-install-3.2"]}} os: linux - compiler: ghc-8.2.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.2.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.2.2","cabal-install-3.2"]}} os: linux - compiler: ghc-8.0.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.0.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.0.2","cabal-install-3.2"]}} os: linux - compiler: ghc-7.10.3 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.10.3","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.10.3","cabal-install-3.2"]}} os: linux - compiler: ghc-7.8.4 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.8.4","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.8.4","cabal-install-3.2"]}} os: linux - compiler: ghc-7.6.3 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.6.3","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.6.3","cabal-install-3.2"]}} os: linux - compiler: ghc-7.4.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.4.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.4.2","cabal-install-3.2"]}} os: linux - compiler: ghc-7.2.2 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.2.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.2.2","cabal-install-3.2"]}} os: linux - compiler: ghc-7.0.4 - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.0.4","cabal-install-3.0"]}} - os: linux - - compiler: ghc-head - addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-head","cabal-install-head"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.0.4","cabal-install-3.2"]}} os: linux allow_failures: - - compiler: ghc-head - compiler: ghc-7.0.4 - compiler: ghc-7.2.2 - - compiler: ghc-8.10.1 before_install: - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//') - WITHCOMPILER="-w $HC" - HADDOCK=$(echo "/opt/$CC/bin/haddock" | sed 's/-/\//') - HCPKG="$HC-pkg" - unset CC - CABAL=/opt/ghc/bin/cabal - CABALHOME=$HOME/.cabal - export PATH="$CABALHOME/bin:$PATH" - TOP=$(pwd) - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')" - echo $HCNUMVER - - CABAL="$CABAL -vnormal+nowrap+markoutput" + - CABAL="$CABAL -vnormal+nowrap" - set -o pipefail - - | - echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk - echo 'BEGIN { state = "output"; }' >> .colorful.awk - echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk - echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk - echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk - echo ' if (state == "cabal") {' >> .colorful.awk - echo ' print blue($0)' >> .colorful.awk - echo ' } else {' >> .colorful.awk - echo ' print $0' >> .colorful.awk - echo ' }' >> .colorful.awk - echo '}' >> .colorful.awk - - cat .colorful.awk - - | - color_cabal_output () { - awk -f $TOP/.colorful.awk - } - - echo text | color_cabal_output -install: - - ${CABAL} --version - - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - TEST=--enable-tests - BENCH=--enable-benchmarks - HEADHACKAGE=false - - if [ $HCNUMVER -ge 81000 ] ; then HEADHACKAGE=true ; fi - rm -f $CABALHOME/config - | - echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config - echo "remote-build-reporting: anonymous" >> $CABALHOME/config - echo "write-ghc-environment-files: always" >> $CABALHOME/config - echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config - echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config - echo "world-file: $CABALHOME/world" >> $CABALHOME/config - echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config - echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config - echo "installdir: $CABALHOME/bin" >> $CABALHOME/config - echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config - echo "store-dir: $CABALHOME/store" >> $CABALHOME/config - echo "install-dirs user" >> $CABALHOME/config - echo " prefix: $CABALHOME" >> $CABALHOME/config - echo "repository hackage.haskell.org" >> $CABALHOME/config - echo " url: http://hackage.haskell.org/" >> $CABALHOME/config - echo " secure: True" >> $CABALHOME/config - echo " key-threshold: 3" >> $CABALHOME/config - echo " root-keys:" >> $CABALHOME/config - echo " fe331502606802feac15e514d9b9ea83fee8b6ffef71335479a2e68d84adc6b0" >> $CABALHOME/config - echo " 1ea9ba32c526d1cc91ab5e5bd364ec5e9e8cb67179a471872f6e26f0ae773d42" >> $CABALHOME/config - echo " 2c6c3627bd6c982990239487f1abd02e08a02e6cf16edb105a8012d444d870c3" >> $CABALHOME/config - echo " 0a5c7ea47cd1b15f01f5f51a33adda7e655bc0f0b0615baa8e271f4c3351e21d" >> $CABALHOME/config - echo " 51f0161b906011b52c6613376b1ae937670da69322113a246a09f807c62f6921" >> $CABALHOME/config - - | - if $HEADHACKAGE; then - echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1/g')" >> $CABALHOME/config - echo "repository head.hackage.ghc.haskell.org" >> $CABALHOME/config - echo " url: https://ghc.gitlab.haskell.org/head.hackage/" >> $CABALHOME/config - echo " secure: True" >> $CABALHOME/config - echo " root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d" >> $CABALHOME/config - echo " 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329" >> $CABALHOME/config - echo " f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89" >> $CABALHOME/config - echo " key-threshold: 3" >> $CABALHOME/config - fi + echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config + echo "remote-build-reporting: anonymous" >> $CABALHOME/config + echo "write-ghc-environment-files: always" >> $CABALHOME/config + echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config + echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config + echo "world-file: $CABALHOME/world" >> $CABALHOME/config + echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config + echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config + echo "installdir: $CABALHOME/bin" >> $CABALHOME/config + echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config + echo "store-dir: $CABALHOME/store" >> $CABALHOME/config + echo "install-dirs user" >> $CABALHOME/config + echo " prefix: $CABALHOME" >> $CABALHOME/config + echo "repository hackage.haskell.org" >> $CABALHOME/config + echo " url: http://hackage.haskell.org/" >> $CABALHOME/config +install: + - ${CABAL} --version + - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - | echo "program-default-options" >> $CABALHOME/config echo " ghc-options: $GHCJOBS +RTS -M6G -RTS" >> $CABALHOME/config - cat $CABALHOME/config - rm -fv cabal.project cabal.project.local cabal.project.freeze - travis_retry ${CABAL} v2-update -v # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | echo "packages: ." >> cabal.project + - if [ $HCNUMVER -ge 80200 ] ; then echo 'package tagged' >> cabal.project ; fi + - "if [ $HCNUMVER -ge 80200 ] ; then echo ' ghc-options: -Werror=missing-methods' >> cabal.project ; fi" - | - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} | color_cabal_output + - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" - rm cabal.project.freeze - - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all | color_cabal_output + - travis_wait 40 ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all script: - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Packaging... - - ${CABAL} v2-sdist all | color_cabal_output + - ${CABAL} v2-sdist all # Unpacking... - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \; - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \; - PKGDIR_tagged="$(find . -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | echo "packages: ${PKGDIR_tagged}" >> cabal.project + - if [ $HCNUMVER -ge 80200 ] ; then echo 'package tagged' >> cabal.project ; fi + - "if [ $HCNUMVER -ge 80200 ] ; then echo ' ghc-options: -Werror=missing-methods' >> cabal.project ; fi" - | - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true # Building with tests and benchmarks... # build & run tests, build benchmarks - - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output + - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all # cabal check... - (cd ${PKGDIR_tagged} && ${CABAL} -vnormal check) # haddock... - - ${CABAL} v2-haddock $WITHCOMPILER --with-haddock $HADDOCK ${TEST} ${BENCH} all | color_cabal_output + - ${CABAL} v2-haddock $WITHCOMPILER --with-haddock $HADDOCK ${TEST} ${BENCH} all -# REGENDATA ("0.9.20191126",["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"]) +# REGENDATA ("0.10",["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"]) # EOF diff --git a/tagged.cabal b/tagged.cabal index b5c9313..75fbb04 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,84 +1,84 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml .travis.yml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 - , GHC == 8.8.1 + , GHC == 8.8.3 , GHC == 8.10.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.17 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
4e4b1c2d9ee481d74607fa0581ed012811f24720
Travis: Don't test GHC HEAD
diff --git a/cabal.haskell-ci b/cabal.haskell-ci index 47b9610..85dd80c 100644 --- a/cabal.haskell-ci +++ b/cabal.haskell-ci @@ -1,5 +1,4 @@ -ghc-head: True no-tests-no-benchmarks: False unconstrained: False allow-failures: <7.3 irc-channels: irc.freenode.org#haskell-lens
ekmett/tagged
c82f6f39cfc7aeeda505e37b627de2528e984b93
Allow building with template-haskell-2.16.*
diff --git a/.travis.yml b/.travis.yml index 0f8cadd..879c5e7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,175 +1,206 @@ # This Travis job script has been generated by a script via # # haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.4 +# version: 0.9.20191126 # +version: ~> 1.0 language: c +os: linux dist: xenial git: # whether to recursively clone submodules submodules: false notifications: irc: channels: - irc.freenode.org#haskell-lens skip_join: true template: - "\"\\x0313tagged\\x03/\\x0306%{branch}\\x03 \\x0314%{commit}\\x03 %{build_url} %{message}\"" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store + - $HOME/.hlint before_cache: - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.* - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $CABALHOME/packages/head.hackage -matrix: +jobs: include: + - compiler: ghc-8.10.1 + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.10.1","cabal-install-3.0"]}} + os: linux - compiler: ghc-8.8.1 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.8.1","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.8.1","cabal-install-3.0"]}} + os: linux - compiler: ghc-8.6.5 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.6.5","cabal-install-3.0"]}} + os: linux - compiler: ghc-8.4.4 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.4.4","cabal-install-3.0"]}} + os: linux - compiler: ghc-8.2.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.2.2","cabal-install-3.0"]}} + os: linux - compiler: ghc-8.0.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.0.2","cabal-install-3.0"]}} + os: linux - compiler: ghc-7.10.3 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.10.3","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.10.3","cabal-install-3.0"]}} + os: linux - compiler: ghc-7.8.4 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.8.4","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.8.4","cabal-install-3.0"]}} + os: linux - compiler: ghc-7.6.3 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.6.3","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.6.3","cabal-install-3.0"]}} + os: linux - compiler: ghc-7.4.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.4.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.4.2","cabal-install-3.0"]}} + os: linux - compiler: ghc-7.2.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.2.2","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.2.2","cabal-install-3.0"]}} + os: linux - compiler: ghc-7.0.4 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.0.4","cabal-install-3.0"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-7.0.4","cabal-install-3.0"]}} + os: linux - compiler: ghc-head - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-head","cabal-install-head"]}} + addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-head","cabal-install-head"]}} + os: linux allow_failures: - compiler: ghc-head - compiler: ghc-7.0.4 - compiler: ghc-7.2.2 + - compiler: ghc-8.10.1 before_install: - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//') - WITHCOMPILER="-w $HC" + - HADDOCK=$(echo "/opt/$CC/bin/haddock" | sed 's/-/\//') - HCPKG="$HC-pkg" - unset CC - CABAL=/opt/ghc/bin/cabal - CABALHOME=$HOME/.cabal - export PATH="$CABALHOME/bin:$PATH" - TOP=$(pwd) - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')" - echo $HCNUMVER - CABAL="$CABAL -vnormal+nowrap+markoutput" - set -o pipefail - | echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk echo 'BEGIN { state = "output"; }' >> .colorful.awk echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk echo ' if (state == "cabal") {' >> .colorful.awk echo ' print blue($0)' >> .colorful.awk echo ' } else {' >> .colorful.awk echo ' print $0' >> .colorful.awk echo ' }' >> .colorful.awk echo '}' >> .colorful.awk - cat .colorful.awk - | color_cabal_output () { awk -f $TOP/.colorful.awk } - echo text | color_cabal_output install: - ${CABAL} --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - TEST=--enable-tests - BENCH=--enable-benchmarks - HEADHACKAGE=false - - if [ $HCNUMVER -gt 80801 ] ; then HEADHACKAGE=true ; fi + - if [ $HCNUMVER -ge 81000 ] ; then HEADHACKAGE=true ; fi - rm -f $CABALHOME/config - | - echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config - echo "remote-build-reporting: anonymous" >> $CABALHOME/config - echo "write-ghc-environment-files: always" >> $CABALHOME/config - echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config - echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config - echo "world-file: $CABALHOME/world" >> $CABALHOME/config - echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config - echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config - echo "installdir: $CABALHOME/bin" >> $CABALHOME/config - echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config - echo "store-dir: $CABALHOME/store" >> $CABALHOME/config - echo "install-dirs user" >> $CABALHOME/config - echo " prefix: $CABALHOME" >> $CABALHOME/config - echo "repository hackage.haskell.org" >> $CABALHOME/config - echo " url: http://hackage.haskell.org/" >> $CABALHOME/config + echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config + echo "remote-build-reporting: anonymous" >> $CABALHOME/config + echo "write-ghc-environment-files: always" >> $CABALHOME/config + echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config + echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config + echo "world-file: $CABALHOME/world" >> $CABALHOME/config + echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config + echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config + echo "installdir: $CABALHOME/bin" >> $CABALHOME/config + echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config + echo "store-dir: $CABALHOME/store" >> $CABALHOME/config + echo "install-dirs user" >> $CABALHOME/config + echo " prefix: $CABALHOME" >> $CABALHOME/config + echo "repository hackage.haskell.org" >> $CABALHOME/config + echo " url: http://hackage.haskell.org/" >> $CABALHOME/config + echo " secure: True" >> $CABALHOME/config + echo " key-threshold: 3" >> $CABALHOME/config + echo " root-keys:" >> $CABALHOME/config + echo " fe331502606802feac15e514d9b9ea83fee8b6ffef71335479a2e68d84adc6b0" >> $CABALHOME/config + echo " 1ea9ba32c526d1cc91ab5e5bd364ec5e9e8cb67179a471872f6e26f0ae773d42" >> $CABALHOME/config + echo " 2c6c3627bd6c982990239487f1abd02e08a02e6cf16edb105a8012d444d870c3" >> $CABALHOME/config + echo " 0a5c7ea47cd1b15f01f5f51a33adda7e655bc0f0b0615baa8e271f4c3351e21d" >> $CABALHOME/config + echo " 51f0161b906011b52c6613376b1ae937670da69322113a246a09f807c62f6921" >> $CABALHOME/config - | if $HEADHACKAGE; then echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1/g')" >> $CABALHOME/config echo "repository head.hackage.ghc.haskell.org" >> $CABALHOME/config echo " url: https://ghc.gitlab.haskell.org/head.hackage/" >> $CABALHOME/config echo " secure: True" >> $CABALHOME/config echo " root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d" >> $CABALHOME/config echo " 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329" >> $CABALHOME/config echo " f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89" >> $CABALHOME/config echo " key-threshold: 3" >> $CABALHOME/config fi + - | + echo "program-default-options" >> $CABALHOME/config + echo " ghc-options: $GHCJOBS +RTS -M6G -RTS" >> $CABALHOME/config - cat $CABALHOME/config - rm -fv cabal.project cabal.project.local cabal.project.freeze - travis_retry ${CABAL} v2-update -v # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | echo "packages: ." >> cabal.project - | - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} | color_cabal_output - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" - rm cabal.project.freeze - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all | color_cabal_output script: - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Packaging... - ${CABAL} v2-sdist all | color_cabal_output # Unpacking... - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \; - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \; - PKGDIR_tagged="$(find . -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | echo "packages: ${PKGDIR_tagged}" >> cabal.project - | - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true # Building with tests and benchmarks... # build & run tests, build benchmarks - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output # cabal check... - (cd ${PKGDIR_tagged} && ${CABAL} -vnormal check) # haddock... - - ${CABAL} v2-haddock $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output + - ${CABAL} v2-haddock $WITHCOMPILER --with-haddock $HADDOCK ${TEST} ${BENCH} all | color_cabal_output -# REGENDATA ["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"] +# REGENDATA ("0.9.20191126",["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"]) # EOF diff --git a/tagged.cabal b/tagged.cabal index bb542b1..b5c9313 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,83 +1,84 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .hlint.yaml .travis.yml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.1 + , GHC == 8.10.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.16 + build-depends: template-haskell >= 2.8 && < 2.17 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
d5f79a0d250304a5b990b937a73d25880471833d
Fully enable GHC 8.8.1 on Travis
diff --git a/.travis.yml b/.travis.yml index 5f9dd1e..0f8cadd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,176 +1,175 @@ # This Travis job script has been generated by a script via # # haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.3.20190425 +# version: 0.4 # language: c dist: xenial git: # whether to recursively clone submodules submodules: false notifications: irc: channels: - irc.freenode.org#haskell-lens skip_join: true template: - "\"\\x0313tagged\\x03/\\x0306%{branch}\\x03 \\x0314%{commit}\\x03 %{build_url} %{message}\"" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.* - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $CABALHOME/packages/head.hackage matrix: include: - compiler: ghc-8.8.1 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.8.1","cabal-install-3.0"]}} - env: GHCHEAD=true - compiler: ghc-8.6.5 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-3.0"]}} - compiler: ghc-8.4.4 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-3.0"]}} - compiler: ghc-8.2.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-3.0"]}} - compiler: ghc-8.0.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-3.0"]}} - compiler: ghc-7.10.3 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.10.3","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.10.3","cabal-install-3.0"]}} - compiler: ghc-7.8.4 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.8.4","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.8.4","cabal-install-3.0"]}} - compiler: ghc-7.6.3 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.6.3","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.6.3","cabal-install-3.0"]}} - compiler: ghc-7.4.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.4.2","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.4.2","cabal-install-3.0"]}} - compiler: ghc-7.2.2 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.2.2","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.2.2","cabal-install-3.0"]}} - compiler: ghc-7.0.4 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.0.4","cabal-install-2.4"]}} + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.0.4","cabal-install-3.0"]}} - compiler: ghc-head addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-head","cabal-install-head"]}} - env: GHCHEAD=true allow_failures: - compiler: ghc-head - compiler: ghc-7.0.4 - compiler: ghc-7.2.2 - - compiler: ghc-8.8.1 before_install: - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//') + - WITHCOMPILER="-w $HC" - HCPKG="$HC-pkg" - unset CC - CABAL=/opt/ghc/bin/cabal - CABALHOME=$HOME/.cabal - export PATH="$CABALHOME/bin:$PATH" - TOP=$(pwd) - - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) + - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')" - echo $HCNUMVER - CABAL="$CABAL -vnormal+nowrap+markoutput" - set -o pipefail - | echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk echo 'BEGIN { state = "output"; }' >> .colorful.awk echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk echo ' if (state == "cabal") {' >> .colorful.awk echo ' print blue($0)' >> .colorful.awk echo ' } else {' >> .colorful.awk echo ' print $0' >> .colorful.awk echo ' }' >> .colorful.awk echo '}' >> .colorful.awk - cat .colorful.awk - | color_cabal_output () { awk -f $TOP/.colorful.awk } - echo text | color_cabal_output install: - ${CABAL} --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - TEST=--enable-tests - BENCH=--enable-benchmarks - - GHCHEAD=${GHCHEAD-false} + - HEADHACKAGE=false + - if [ $HCNUMVER -gt 80801 ] ; then HEADHACKAGE=true ; fi - rm -f $CABALHOME/config - | echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config echo "remote-build-reporting: anonymous" >> $CABALHOME/config + echo "write-ghc-environment-files: always" >> $CABALHOME/config echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config echo "world-file: $CABALHOME/world" >> $CABALHOME/config echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config echo "installdir: $CABALHOME/bin" >> $CABALHOME/config echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config echo "store-dir: $CABALHOME/store" >> $CABALHOME/config echo "install-dirs user" >> $CABALHOME/config echo " prefix: $CABALHOME" >> $CABALHOME/config echo "repository hackage.haskell.org" >> $CABALHOME/config echo " url: http://hackage.haskell.org/" >> $CABALHOME/config - | - if $GHCHEAD; then + if $HEADHACKAGE; then echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1/g')" >> $CABALHOME/config - - echo "repository head.hackage" >> $CABALHOME/config - echo " url: http://head.hackage.haskell.org/" >> $CABALHOME/config + echo "repository head.hackage.ghc.haskell.org" >> $CABALHOME/config + echo " url: https://ghc.gitlab.haskell.org/head.hackage/" >> $CABALHOME/config echo " secure: True" >> $CABALHOME/config - echo " root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740" >> $CABALHOME/config - echo " 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb" >> $CABALHOME/config - echo " 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e" >> $CABALHOME/config + echo " root-keys: 7541f32a4ccca4f97aea3b22f5e593ba2c0267546016b992dfadcd2fe944e55d" >> $CABALHOME/config + echo " 26021a13b401500c8eb2761ca95c61f2d625bfef951b939a8124ed12ecf07329" >> $CABALHOME/config + echo " f76d08be13e9a61a377a85e2fb63f4c5435d40f8feb3e12eb05905edb8cdea89" >> $CABALHOME/config echo " key-threshold: 3" >> $CABALHOME/config fi - cat $CABALHOME/config - rm -fv cabal.project cabal.project.local cabal.project.freeze - travis_retry ${CABAL} v2-update -v # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | - echo 'packages: "."' >> cabal.project + echo "packages: ." >> cabal.project - | - echo "write-ghc-environment-files: always" >> cabal.project - - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" + - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - - ${CABAL} v2-freeze -w ${HC} ${TEST} ${BENCH} | color_cabal_output + - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} | color_cabal_output - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" - rm cabal.project.freeze - - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} --dep -j2 all | color_cabal_output + - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all | color_cabal_output script: - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Packaging... - ${CABAL} v2-sdist all | color_cabal_output # Unpacking... - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; + - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \; + - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \; + - PKGDIR_tagged="$(find . -maxdepth 1 -type d -regex '.*/tagged-[0-9.]*')" # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | - echo 'packages: "tagged-*/*.cabal"' >> cabal.project + echo "packages: ${PKGDIR_tagged}" >> cabal.project - | - echo "write-ghc-environment-files: always" >> cabal.project - - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" + - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(tagged)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true # Building with tests and benchmarks... # build & run tests, build benchmarks - - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} all | color_cabal_output + - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output # cabal check... - - (cd tagged-* && ${CABAL} -vnormal check) + - (cd ${PKGDIR_tagged} && ${CABAL} -vnormal check) # haddock... - - ${CABAL} v2-haddock -w ${HC} ${TEST} ${BENCH} all | color_cabal_output + - ${CABAL} v2-haddock $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output # REGENDATA ["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"] # EOF
ekmett/tagged
2d7b2dea8f65f20629ae2c8e7470994dff017f60
Migrate HLint.hs to YAML
diff --git a/.hlint.yaml b/.hlint.yaml new file mode 100644 index 0000000..693283c --- /dev/null +++ b/.hlint.yaml @@ -0,0 +1,4 @@ +- arguments: [--cpp-define=HLINT, --cpp-ansi] + +- ignore: {name: Use camelCase} +- ignore: {name: Eta reduce} diff --git a/HLint.hs b/HLint.hs deleted file mode 100644 index 52eb49d..0000000 --- a/HLint.hs +++ /dev/null @@ -1,2 +0,0 @@ -ignore "Use camelCase" -ignore "Eta reduce" diff --git a/tagged.cabal b/tagged.cabal index b44d959..bb542b1 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,83 +1,83 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 -extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs +extra-source-files: .hlint.yaml .travis.yml CHANGELOG.markdown README.markdown tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.5 , GHC == 8.8.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.16 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
050df77e1ab2580800c634fd6239a49e34b24c8b
Regenerate .travis.yml
diff --git a/.travis.yml b/.travis.yml index 98b5d7e..5f9dd1e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,176 +1,176 @@ # This Travis job script has been generated by a script via # # haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # # version: 0.3.20190425 # language: c dist: xenial git: # whether to recursively clone submodules submodules: false notifications: irc: channels: - irc.freenode.org#haskell-lens skip_join: true template: - "\"\\x0313tagged\\x03/\\x0306%{branch}\\x03 \\x0314%{commit}\\x03 %{build_url} %{message}\"" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.* - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $CABALHOME/packages/head.hackage matrix: include: - compiler: ghc-8.8.1 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.8.1","cabal-install-3.0"]}} env: GHCHEAD=true - - compiler: ghc-8.6.4 - addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.4","cabal-install-2.4"]}} + - compiler: ghc-8.6.5 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-2.4"]}} - compiler: ghc-8.4.4 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-2.4"]}} - compiler: ghc-8.2.2 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-2.4"]}} - compiler: ghc-8.0.2 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-2.4"]}} - compiler: ghc-7.10.3 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.10.3","cabal-install-2.4"]}} - compiler: ghc-7.8.4 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.8.4","cabal-install-2.4"]}} - compiler: ghc-7.6.3 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.6.3","cabal-install-2.4"]}} - compiler: ghc-7.4.2 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.4.2","cabal-install-2.4"]}} - compiler: ghc-7.2.2 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.2.2","cabal-install-2.4"]}} - compiler: ghc-7.0.4 addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.0.4","cabal-install-2.4"]}} - compiler: ghc-head addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-head","cabal-install-head"]}} env: GHCHEAD=true allow_failures: - compiler: ghc-head - compiler: ghc-7.0.4 - compiler: ghc-7.2.2 - compiler: ghc-8.8.1 before_install: - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//') - HCPKG="$HC-pkg" - unset CC - CABAL=/opt/ghc/bin/cabal - CABALHOME=$HOME/.cabal - export PATH="$CABALHOME/bin:$PATH" - TOP=$(pwd) - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER - CABAL="$CABAL -vnormal+nowrap+markoutput" - set -o pipefail - | echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk echo 'BEGIN { state = "output"; }' >> .colorful.awk echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk echo ' if (state == "cabal") {' >> .colorful.awk echo ' print blue($0)' >> .colorful.awk echo ' } else {' >> .colorful.awk echo ' print $0' >> .colorful.awk echo ' }' >> .colorful.awk echo '}' >> .colorful.awk - cat .colorful.awk - | color_cabal_output () { awk -f $TOP/.colorful.awk } - echo text | color_cabal_output install: - ${CABAL} --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - TEST=--enable-tests - BENCH=--enable-benchmarks - GHCHEAD=${GHCHEAD-false} - rm -f $CABALHOME/config - | echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config echo "remote-build-reporting: anonymous" >> $CABALHOME/config echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config echo "world-file: $CABALHOME/world" >> $CABALHOME/config echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config echo "installdir: $CABALHOME/bin" >> $CABALHOME/config echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config echo "store-dir: $CABALHOME/store" >> $CABALHOME/config echo "install-dirs user" >> $CABALHOME/config echo " prefix: $CABALHOME" >> $CABALHOME/config echo "repository hackage.haskell.org" >> $CABALHOME/config echo " url: http://hackage.haskell.org/" >> $CABALHOME/config - | if $GHCHEAD; then echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1/g')" >> $CABALHOME/config echo "repository head.hackage" >> $CABALHOME/config echo " url: http://head.hackage.haskell.org/" >> $CABALHOME/config echo " secure: True" >> $CABALHOME/config echo " root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740" >> $CABALHOME/config echo " 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb" >> $CABALHOME/config echo " 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e" >> $CABALHOME/config echo " key-threshold: 3" >> $CABALHOME/config fi - cat $CABALHOME/config - rm -fv cabal.project cabal.project.local cabal.project.freeze - travis_retry ${CABAL} v2-update -v # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | echo 'packages: "."' >> cabal.project - | echo "write-ghc-environment-files: always" >> cabal.project - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - ${CABAL} v2-freeze -w ${HC} ${TEST} ${BENCH} | color_cabal_output - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" - rm cabal.project.freeze - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} --dep -j2 all | color_cabal_output script: - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Packaging... - ${CABAL} v2-sdist all | color_cabal_output # Unpacking... - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; # Generate cabal.project - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - | echo 'packages: "tagged-*/*.cabal"' >> cabal.project - | echo "write-ghc-environment-files: always" >> cabal.project - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true # Building with tests and benchmarks... # build & run tests, build benchmarks - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} all | color_cabal_output # cabal check... - (cd tagged-* && ${CABAL} -vnormal check) # haddock... - ${CABAL} v2-haddock -w ${HC} ${TEST} ${BENCH} all | color_cabal_output # REGENDATA ["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index e72a19d..b44d959 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,83 +1,83 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 - , GHC == 8.6.4 + , GHC == 8.6.5 , GHC == 8.8.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.16 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
f2090bc620feda0a9658157b1b94453ee71616b0
Bump template-haskell bounds (#48)
diff --git a/.travis.yml b/.travis.yml index ccee2e9..98b5d7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,153 +1,176 @@ # This Travis job script has been generated by a script via # # haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # -# version: 0.2.1 +# version: 0.3.20190425 # language: c dist: xenial - git: - submodules: false # whether to recursively clone submodules - + # whether to recursively clone submodules + submodules: false notifications: irc: channels: - - "irc.freenode.org#haskell-lens" + - irc.freenode.org#haskell-lens skip_join: true template: - - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" - + - "\"\\x0313tagged\\x03/\\x0306%{branch}\\x03 \\x0314%{commit}\\x03 %{build_url} %{message}\"" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store - before_cache: - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.* - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx - - rm -rfv $CABALHOME/packages/head.hackage - matrix: include: - - compiler: "ghc-8.6.4" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.4], sources: [hvr-ghc]}} - - compiler: "ghc-8.4.4" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.4.4], sources: [hvr-ghc]}} - - compiler: "ghc-8.2.2" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.2.2], sources: [hvr-ghc]}} - - compiler: "ghc-8.0.2" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.0.2], sources: [hvr-ghc]}} - - compiler: "ghc-7.10.3" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.10.3], sources: [hvr-ghc]}} - - compiler: "ghc-7.8.4" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.8.4], sources: [hvr-ghc]}} - - compiler: "ghc-7.6.3" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.6.3], sources: [hvr-ghc]}} - - compiler: "ghc-7.4.2" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.4.2], sources: [hvr-ghc]}} - - compiler: "ghc-7.2.2" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.2.2], sources: [hvr-ghc]}} - - compiler: "ghc-7.0.4" - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.0.4], sources: [hvr-ghc]}} - - compiler: "ghc-head" + - compiler: ghc-8.8.1 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.8.1","cabal-install-3.0"]}} + env: GHCHEAD=true + - compiler: ghc-8.6.4 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.4","cabal-install-2.4"]}} + - compiler: ghc-8.4.4 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-2.4"]}} + - compiler: ghc-8.2.2 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-2.4"]}} + - compiler: ghc-8.0.2 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-2.4"]}} + - compiler: ghc-7.10.3 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.10.3","cabal-install-2.4"]}} + - compiler: ghc-7.8.4 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.8.4","cabal-install-2.4"]}} + - compiler: ghc-7.6.3 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.6.3","cabal-install-2.4"]}} + - compiler: ghc-7.4.2 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.4.2","cabal-install-2.4"]}} + - compiler: ghc-7.2.2 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.2.2","cabal-install-2.4"]}} + - compiler: ghc-7.0.4 + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.0.4","cabal-install-2.4"]}} + - compiler: ghc-head + addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-head","cabal-install-head"]}} env: GHCHEAD=true - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} - allow_failures: - - compiler: "ghc-head" - - compiler: "ghc-7.0.4" - - compiler: "ghc-7.2.2" - + - compiler: ghc-head + - compiler: ghc-7.0.4 + - compiler: ghc-7.2.2 + - compiler: ghc-8.8.1 before_install: - - HC=/opt/ghc/bin/${CC} - - HCPKG=${HC/ghc/ghc-pkg} + - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//') + - HCPKG="$HC-pkg" - unset CC - CABAL=/opt/ghc/bin/cabal - CABALHOME=$HOME/.cabal - export PATH="$CABALHOME/bin:$PATH" - - ROOTDIR=$(pwd) + - TOP=$(pwd) - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER - + - CABAL="$CABAL -vnormal+nowrap+markoutput" + - set -o pipefail + - | + echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk + echo 'BEGIN { state = "output"; }' >> .colorful.awk + echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk + echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk + echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk + echo ' if (state == "cabal") {' >> .colorful.awk + echo ' print blue($0)' >> .colorful.awk + echo ' } else {' >> .colorful.awk + echo ' print $0' >> .colorful.awk + echo ' }' >> .colorful.awk + echo '}' >> .colorful.awk + - cat .colorful.awk + - | + color_cabal_output () { + awk -f $TOP/.colorful.awk + } + - echo text | color_cabal_output install: - ${CABAL} --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - TEST=--enable-tests - BENCH=--enable-benchmarks - GHCHEAD=${GHCHEAD-false} - - travis_retry ${CABAL} update -v - - sed -i.bak 's/^jobs:/-- jobs:/' $CABALHOME/config - - rm -fv cabal.project cabal.project.local - # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage + - rm -f $CABALHOME/config + - | + echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config + echo "remote-build-reporting: anonymous" >> $CABALHOME/config + echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config + echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config + echo "world-file: $CABALHOME/world" >> $CABALHOME/config + echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config + echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config + echo "installdir: $CABALHOME/bin" >> $CABALHOME/config + echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config + echo "store-dir: $CABALHOME/store" >> $CABALHOME/config + echo "install-dirs user" >> $CABALHOME/config + echo " prefix: $CABALHOME" >> $CABALHOME/config + echo "repository hackage.haskell.org" >> $CABALHOME/config + echo " url: http://hackage.haskell.org/" >> $CABALHOME/config - | if $GHCHEAD; then - sed -i 's/-- allow-newer: .*/allow-newer: *:base/' $CABALHOME/config - for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" $CABALHOME/config; done - - echo 'repository head.hackage' >> $CABALHOME/config - echo ' url: http://head.hackage.haskell.org/' >> $CABALHOME/config - echo ' secure: True' >> $CABALHOME/config - echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> $CABALHOME/config - echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> $CABALHOME/config - echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> $CABALHOME/config - echo ' key-threshold: 3' >> $CABALHOME.config - - grep -Ev -- '^\s*--' $CABALHOME/config | grep -Ev '^\s*$' - - ${CABAL} new-update head.hackage -v + echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1/g')" >> $CABALHOME/config + + echo "repository head.hackage" >> $CABALHOME/config + echo " url: http://head.hackage.haskell.org/" >> $CABALHOME/config + echo " secure: True" >> $CABALHOME/config + echo " root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740" >> $CABALHOME/config + echo " 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb" >> $CABALHOME/config + echo " 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e" >> $CABALHOME/config + echo " key-threshold: 3" >> $CABALHOME/config fi - - grep -Ev -- '^\s*--' $CABALHOME/config | grep -Ev '^\s*$' - - rm -f cabal.project + - cat $CABALHOME/config + - rm -fv cabal.project cabal.project.local cabal.project.freeze + - travis_retry ${CABAL} v2-update -v + # Generate cabal.project + - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - - "printf 'packages: \".\"\\n' >> cabal.project" - - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - - touch cabal.project.local + - | + echo 'packages: "."' >> cabal.project + - | + echo "write-ghc-environment-files: always" >> cabal.project - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - - rm -f cabal.project.freeze - - ${CABAL} new-freeze -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dry - - "cat \"cabal.project.freeze\" | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" - - rm "cabal.project.freeze" - - ${CABAL} new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - - rm -rf .ghc.environment.* "."/dist - - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) - -# Here starts the actual work to be performed for the package under test; -# any command which exits with a non-zero exit code causes the build to fail. + - ${CABAL} v2-freeze -w ${HC} ${TEST} ${BENCH} | color_cabal_output + - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" + - rm cabal.project.freeze + - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} --dep -j2 all | color_cabal_output script: - # test that source-distributions can be generated - - ${CABAL} new-sdist all + - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) + # Packaging... + - ${CABAL} v2-sdist all | color_cabal_output + # Unpacking... - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - - rm -f cabal.project + # Generate cabal.project + - rm -rf cabal.project cabal.project.local cabal.project.freeze - touch cabal.project - - "printf 'packages: \"tagged-*/*.cabal\"\\n' >> cabal.project" - - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - - touch cabal.project.local + - | + echo 'packages: "tagged-*/*.cabal"' >> cabal.project + - | + echo "write-ghc-environment-files: always" >> cabal.project - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true - + # Building with tests and benchmarks... # build & run tests, build benchmarks - - ${CABAL} new-build -w ${HC} ${TEST} ${BENCH} all - - # cabal check - - (cd tagged-* && ${CABAL} check) - - # haddock - - ${CABAL} new-haddock -w ${HC} ${TEST} ${BENCH} all + - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} all | color_cabal_output + # cabal check... + - (cd tagged-* && ${CABAL} -vnormal check) + # haddock... + - ${CABAL} v2-haddock -w ${HC} ${TEST} ${BENCH} all | color_cabal_output # REGENDATA ["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index 57c5150..e72a19d 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,82 +1,83 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 , GHC == 8.6.4 + , GHC == 8.8.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.15 + build-depends: template-haskell >= 2.8 && < 2.16 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
c07d447209ed2fc8dc0f933e843a5e0d4713f268
Regenerate .travis.yml
diff --git a/.travis.yml b/.travis.yml index 862a4cb..ccee2e9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,158 +1,153 @@ # This Travis job script has been generated by a script via # -# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' '--allow-failure=7.0.4' '--allow-failure=7.2.2' 'cabal.project' +# haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # +# version: 0.2.1 +# language: c -sudo: false +dist: xenial git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log + - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx + - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.* + - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json + - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache + - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar + - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx - - rm -rfv $HOME/.cabal/packages/head.hackage + - rm -rfv $CABALHOME/packages/head.hackage matrix: include: - - compiler: "ghc-8.6.3" - # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.3], sources: [hvr-ghc]}} + - compiler: "ghc-8.6.4" + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.4], sources: [hvr-ghc]}} - compiler: "ghc-8.4.4" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.4.4], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.0.4" - # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-head" - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" before_install: - - HC=${CC} + - HC=/opt/ghc/bin/${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC + - CABAL=/opt/ghc/bin/cabal + - CABALHOME=$HOME/.cabal + - export PATH="$CABALHOME/bin:$PATH" - ROOTDIR=$(pwd) - - mkdir -p $HOME/.local/bin - - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - - cabal --version + - ${CABAL} --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - - BENCH=${BENCH---enable-benchmarks} - - TEST=${TEST---enable-tests} - - HADDOCK=${HADDOCK-true} - - UNCONSTRAINED=${UNCONSTRAINED-true} - - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false} + - TEST=--enable-tests + - BENCH=--enable-benchmarks - GHCHEAD=${GHCHEAD-false} - - travis_retry cabal update -v - - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" + - travis_retry ${CABAL} update -v + - sed -i.bak 's/^jobs:/-- jobs:/' $CABALHOME/config - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then - sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config - for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done + sed -i 's/-- allow-newer: .*/allow-newer: *:base/' $CABALHOME/config + for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" $CABALHOME/config; done - echo 'repository head.hackage' >> ${HOME}/.cabal/config - echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config - echo ' secure: True' >> ${HOME}/.cabal/config - echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config - echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config - echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config - echo ' key-threshold: 3' >> ${HOME}/.cabal.config + echo 'repository head.hackage' >> $CABALHOME/config + echo ' url: http://head.hackage.haskell.org/' >> $CABALHOME/config + echo ' secure: True' >> $CABALHOME/config + echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> $CABALHOME/config + echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> $CABALHOME/config + echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> $CABALHOME/config + echo ' key-threshold: 3' >> $CABALHOME.config - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' + grep -Ev -- '^\s*--' $CABALHOME/config | grep -Ev '^\s*$' - cabal new-update head.hackage -v + ${CABAL} new-update head.hackage -v fi - - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - - "printf 'packages: \".\"\\n' > cabal.project" + - grep -Ev -- '^\s*--' $CABALHOME/config | grep -Ev '^\s*$' + - rm -f cabal.project + - touch cabal.project + - "printf 'packages: \".\"\\n' >> cabal.project" - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - touch cabal.project.local - - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" + - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true - - if [ -f "./configure.ac" ]; then - (cd "." && autoreconf -i); - fi + - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all + - ${CABAL} new-freeze -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dry + - "cat \"cabal.project.freeze\" | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'" + - rm "cabal.project.freeze" + - ${CABAL} new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - - cabal new-sdist all + - ${CABAL} new-sdist all - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" + - rm -f cabal.project + - touch cabal.project + - "printf 'packages: \"tagged-*/*.cabal\"\\n' >> cabal.project" - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - touch cabal.project.local - - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" + - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(tagged)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true # build & run tests, build benchmarks - - cabal new-build -w ${HC} ${TEST} ${BENCH} all + - ${CABAL} new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - - (cd tagged-* && cabal check) + - (cd tagged-* && ${CABAL} check) # haddock - - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi + - ${CABAL} new-haddock -w ${HC} ${TEST} ${BENCH} all # REGENDATA ["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index fcb5c94..57c5150 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,82 +1,82 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 - , GHC == 8.6.3 + , GHC == 8.6.4 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
11970f44e0fbb29e2878e09f62566705ad626c86
Factor out haskell-ci configuration
diff --git a/.travis.yml b/.travis.yml index e9d7f06..862a4cb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,158 +1,158 @@ # This Travis job script has been generated by a script via # # runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' '--allow-failure=7.0.4' '--allow-failure=7.2.2' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage matrix: include: - compiler: "ghc-8.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.3], sources: [hvr-ghc]}} - compiler: "ghc-8.4.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.4.4], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-head" - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - UNCONSTRAINED=${UNCONSTRAINED-true} - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - cabal new-sdist all - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi -# REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","--allow-failure=7.0.4","--allow-failure=7.2.2","cabal.project"] +# REGENDATA ["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"] # EOF diff --git a/cabal.haskell-ci b/cabal.haskell-ci new file mode 100644 index 0000000..47b9610 --- /dev/null +++ b/cabal.haskell-ci @@ -0,0 +1,5 @@ +ghc-head: True +no-tests-no-benchmarks: False +unconstrained: False +allow-failures: <7.3 +irc-channels: irc.freenode.org#haskell-lens
ekmett/tagged
fc0073d929241ff4607ce1bcaafc1e9585b27e68
Regenerate .travis.yml
diff --git a/.travis.yml b/.travis.yml index dd90e50..e9d7f06 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,156 +1,158 @@ # This Travis job script has been generated by a script via # # runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' '--allow-failure=7.0.4' '--allow-failure=7.2.2' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage matrix: include: - - compiler: "ghc-8.6.2" + - compiler: "ghc-8.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.3], sources: [hvr-ghc]}} - compiler: "ghc-8.4.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.4.4], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-head" - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - UNCONSTRAINED=${UNCONSTRAINED-true} - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" + - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - cabal new-sdist all - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" + - "printf 'write-ghc-environment-files: always\\n' >> cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi # REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","--allow-failure=7.0.4","--allow-failure=7.2.2","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index cf41396..fcb5c94 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,82 +1,82 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 - , GHC == 8.6.2 + , GHC == 8.6.3 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
dfe192efd88dc921f7a093615798d28a8a4d6d6d
Regenerate .travis.yml
diff --git a/.travis.yml b/.travis.yml index 6f87663..dd90e50 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,156 +1,156 @@ # This Travis job script has been generated by a script via # # runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' '--allow-failure=7.0.4' '--allow-failure=7.2.2' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage matrix: include: - - compiler: "ghc-8.6.1" + - compiler: "ghc-8.6.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.1], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.2], sources: [hvr-ghc]}} - compiler: "ghc-8.4.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.4.4], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-head" - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - UNCONSTRAINED=${UNCONSTRAINED-true} - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - cabal new-sdist all - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi # REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","--allow-failure=7.0.4","--allow-failure=7.2.2","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index d236295..cf41396 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,82 +1,82 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.4 - , GHC == 8.6.1 + , GHC == 8.6.2 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
f237fc4138e3da0d5e896429dfa902b8ae1feba1
Regenerate .travis.yml
diff --git a/.travis.yml b/.travis.yml index 7f6e5b6..6f87663 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,157 +1,156 @@ # This Travis job script has been generated by a script via # # runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' '--allow-failure=7.0.4' '--allow-failure=7.2.2' 'cabal.project' # # For more information, see https://github.com/haskell-CI/haskell-ci # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage matrix: include: - compiler: "ghc-8.6.1" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-8.6.1], sources: [hvr-ghc]}} - - compiler: "ghc-8.4.3" + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.6.1], sources: [hvr-ghc]}} + - compiler: "ghc-8.4.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.4.3], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.4.4], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.2.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.0.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.10.3], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.8.4], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.6.3], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.4.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.2.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.0.4], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.4,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-head" - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - UNCONSTRAINED=${UNCONSTRAINED-true} - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - - (cd "." && cabal sdist) - - mv "."/dist/tagged-*.tar.gz ${DISTDIR}/ + - cabal new-sdist all + - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - touch cabal.project.local - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - - rm -rf ./dist-newstyle - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi # REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","--allow-failure=7.0.4","--allow-failure=7.2.2","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index 5fc399b..d236295 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,82 +1,82 @@ name: tagged version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 - , GHC == 8.4.3 + , GHC == 8.4.4 , GHC == 8.6.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
5f6945a876779f5e9f59d9381088b9b789ce09b8
Travis: Fully enable GHC 8.6
diff --git a/.travis.yml b/.travis.yml index b93a207..7f6e5b6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,158 +1,157 @@ # This Travis job script has been generated by a script via # -# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' 'cabal.project' +# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' '--allow-failure=7.0.4' '--allow-failure=7.2.2' 'cabal.project' # -# For more information, see https://github.com/hvr/multi-ghc-travis +# For more information, see https://github.com/haskell-CI/haskell-ci # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage matrix: include: - compiler: "ghc-8.6.1" - env: GHCHEAD=true + # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-8.6.1], sources: [hvr-ghc]}} - compiler: "ghc-8.4.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.4.3], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-head" - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" - - compiler: "ghc-8.6.1" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - UNCONSTRAINED=${UNCONSTRAINED-true} - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - touch cabal.project.local - - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" + - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - (cd "." && cabal sdist) - mv "."/dist/tagged-*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - touch cabal.project.local - - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" + - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | grep -vw -- tagged | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" - cat cabal.project || true - cat cabal.project.local || true # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - rm -rf ./dist-newstyle - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi -# REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","cabal.project"] +# REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","--allow-failure=7.0.4","--allow-failure=7.2.2","cabal.project"] # EOF
ekmett/tagged
110f5e4fe50522938f87236bffeece5dd69d8557
Version 0.8.6
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 268fe72..0d85056 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,89 +1,89 @@ -next [????.??.??] ------------------ +0.8.6 [2018.07.02] +------------------ * Make the `Read(1)` instances for `Proxy` ignore the precedence argument, mirroring similar changes to `base` [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). * Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was defined in terms of `(**)`. * Avoid incurring some dependencies when using recent GHCs. 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support diff --git a/tagged.cabal b/tagged.cabal index 931b40f..5fc399b 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,82 +1,82 @@ name: tagged -version: 0.8.5 +version: 0.8.6 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.3 , GHC == 8.6.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
f963cc361c7b14e1d8eac11bac7c6f041315d9f4
Add dist-newstyle/ to .gitignore
diff --git a/.gitignore b/.gitignore index cf135d9..2fd3fb8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,33 @@ dist/ +dist-newstyle/ .hsenv/ docs wiki TAGS tags wip .DS_Store .*.swp .*.swo *.o *.hi *~ *# .stack-work/ cabal-dev *.chi *.chs.h *.dyn_o *.dyn_hi .hpc .hsenv .cabal-sandbox/ cabal.sandbox.config *.prof *.aux *.hp *.eventlog cabal.project.local cabal.project.local~ .HTF/ .ghc.environment.*
ekmett/tagged
5112246f13d3fa486111b6f7bccd137e607062da
Travis: GHC 8.6.1
diff --git a/.travis.yml b/.travis.yml index 25fb111..b93a207 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,152 +1,158 @@ # This Travis job script has been generated by a script via # -# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-installed' 'cabal.project' +# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' 'cabal.project' # # For more information, see https://github.com/hvr/multi-ghc-travis # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage -addons: - apt: - packages: &apt_packages - - ghc-ppa-tools - - alex-3.1.4 - - happy-1.19.5 - matrix: include: + - compiler: "ghc-8.6.1" + env: GHCHEAD=true + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-8.6.1], sources: [hvr-ghc]}} - compiler: "ghc-8.4.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.2,ghc-8.4.3], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.4.3], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.2.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.0.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.10.3], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.8.4], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.6.3], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.4.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.2.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.0.4], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true - addons: {apt: {packages: [*apt_packages,cabal-install-head,ghc-head], sources: [hvr-ghc]}} + addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: + - compiler: "ghc-head" - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" - - compiler: "ghc-head" + - compiler: "ghc-8.6.1" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - - INSTALLED=${INSTALLED-true} + - UNCONSTRAINED=${UNCONSTRAINED-true} + - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then - sed -i.bak 's/-- allow-newer:.*/allow-newer: *:base, *:template-haskell, *:ghc, *:Cabal/' ${HOME}/.cabal/config + sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config + for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config + grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' + cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - - cat cabal.project + - touch cabal.project.local + - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" + - cat cabal.project || true + - cat cabal.project.local || true - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - (cd "." && cabal sdist) - mv "."/dist/tagged-*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - - cat cabal.project - + - touch cabal.project.local + - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi" + - cat cabal.project || true + - cat cabal.project.local || true # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - rm -rf ./dist-newstyle - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi -# REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-installed","cabal.project"] +# REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index b72e6d4..931b40f 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,81 +1,82 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.3 + , GHC == 8.6.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
82d3aaa918bde596e6d03ac77e74a1d8f3fd38d6
Mention #41 and #43 in the CHANGELOG
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index 665207d..268fe72 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -1,80 +1,89 @@ +next [????.??.??] +----------------- +* Make the `Read(1)` instances for `Proxy` ignore the precedence argument, + mirroring similar changes to `base` + [here](http://git.haskell.org/ghc.git/commitdiff/8fd959998e900dffdb7f752fcd42df7aaedeae6e). +* Fix a bug in the `Floating` instance for `Tagged` in which `logBase` was + defined in terms of `(**)`. +* Avoid incurring some dependencies when using recent GHCs. + 0.8.5 ----- * Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. * Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` * Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` 0.8.4 ----- * Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` * Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` 0.8.3 ----- * Manual `Generic1` support to work around a bug in GHC 7.6 * Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 0.8.2 ------- * `deepseq` support. * Widened `template-haskell` dependency bounds. 0.8.1 ----- * Add `KProxy` to the backwards compatibility `Data.Proxy` module. * Add a `Generic` instance to `Proxy`. 0.8.0.1 ------- * Fix builds on GHC 7.4. 0.8 --- * Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. * Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. 0.7.3 --- * Support `Data.Bifunctor` in `base` for GHC 7.9+. 0.7.2 ----- * Fixed warning on GHC 7.8 0.7.1 ----- * Added `tagWith`. 0.7 --- * `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of the `reproxy` function. 0.6.2 ----- * Allowed polymorphic arguments where possible. 0.6.1 ----- * Needlessly claim that this entirely pure package is `Trustworthy`! 0.6 --- * On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. 0.5 --- * On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. 0.4.5 ----- * Added `witness` 0.4.4 ----- * Actually working polymorphic kind support 0.4.3 ----- * Added polymorphic kind support
ekmett/tagged
c96e19b44e5ea5ee96574aa7e449297cd82d9fd4
Check for GHCJS with impl
diff --git a/tagged.cabal b/tagged.cabal index f83740d..b72e6d4 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,81 +1,81 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.3 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available - if impl(ghc >= 7.10) + if impl(ghc >= 7.10) || impl(ghcjs) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
a50db84e4fbcb7d2f62f744ea687cf6827b2d27a
Allow template-haskell-2.14
diff --git a/tagged.cabal b/tagged.cabal index 98d8ac6..f83740d 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,81 +1,81 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.3 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.14 + build-depends: template-haskell >= 2.8 && < 2.15 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
5ebc938cea8013a8656be63ef7ee93e9870e8212
Use GHC 8.4.3 on Travis
diff --git a/.travis.yml b/.travis.yml index 3004d0c..25fb111 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,152 +1,152 @@ # This Travis job script has been generated by a script via # -# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-installed' 'cabal.project' +# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-installed' 'cabal.project' # # For more information, see https://github.com/hvr/multi-ghc-travis # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage addons: apt: packages: &apt_packages - ghc-ppa-tools - alex-3.1.4 - happy-1.19.5 matrix: include: - - compiler: "ghc-7.0.4" + - compiler: "ghc-8.4.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.0.4], sources: [hvr-ghc]}} - - compiler: "ghc-7.2.2" + addons: {apt: {packages: [*apt_packages,cabal-install-2.2,ghc-8.4.3], sources: [hvr-ghc]}} + - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.2.2], sources: [hvr-ghc]}} - - compiler: "ghc-7.4.2" + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.2.2], sources: [hvr-ghc]}} + - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.4.2], sources: [hvr-ghc]}} - - compiler: "ghc-7.6.3" + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.0.2], sources: [hvr-ghc]}} + - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.6.3], sources: [hvr-ghc]}} + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.8.4], sources: [hvr-ghc]}} - - compiler: "ghc-7.10.3" + - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.10.3], sources: [hvr-ghc]}} - - compiler: "ghc-8.0.2" + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.6.3], sources: [hvr-ghc]}} + - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.0.2], sources: [hvr-ghc]}} - - compiler: "ghc-8.2.2" + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.4.2], sources: [hvr-ghc]}} + - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.2.2], sources: [hvr-ghc]}} - - compiler: "ghc-8.4.2" + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.2.2], sources: [hvr-ghc]}} + - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.2,ghc-8.4.2], sources: [hvr-ghc]}} + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [*apt_packages,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" - compiler: "ghc-head" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - INSTALLED=${INSTALLED-true} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i.bak 's/-- allow-newer:.*/allow-newer: *:base, *:template-haskell, *:ghc, *:Cabal/' ${HOME}/.cabal/config echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - cat cabal.project - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - - rm -rf "."/.ghc.environment.* "."/dist + - rm -rf .ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - (cd "." && cabal sdist) - mv "."/dist/tagged-*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - cat cabal.project # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - rm -rf ./dist-newstyle - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi -# REGENDATA ["-o",".travis.yml","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-installed","cabal.project"] +# REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-installed","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index c86d50a..98d8ac6 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,81 +1,81 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 - , GHC == 8.4.2 + , GHC == 8.4.3 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.14 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 -- Ensure Data.Functor.Classes is always available if impl(ghc >= 7.10) build-depends: transformers >= 0.4.2.0 else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
3e7eb3156a919fbfc607bbbc8e059c41cbdb7ae5
Fix build with GHC-7.8 (#44)
diff --git a/tagged.cabal b/tagged.cabal index 75068e0..c86d50a 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,77 +1,81 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.2 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.14 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6 - if !impl(ghc > 7.8) + + -- Ensure Data.Functor.Classes is always available + if impl(ghc >= 7.10) + build-depends: transformers >= 0.4.2.0 + else build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
52157b1da0ee9fbcd39dd8fb7922cac84d68cb6c
tidy up dependencies
diff --git a/tagged.cabal b/tagged.cabal index f40f619..75068e0 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,76 +1,77 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.2 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.14 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) - build-depends: transformers >= 0.2 && < 0.6, - transformers-compat >= 0.5 && < 1 + build-depends: transformers >= 0.2 && < 0.6 + if !impl(ghc > 7.8) + build-depends: transformers-compat >= 0.5 && < 1
ekmett/tagged
52526fae684c0fb7acbf3acc1b3d2bd626bd23cd
Use GHC 8.4.2 on Travis
diff --git a/.travis.yml b/.travis.yml index c7be4b6..3004d0c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,152 +1,152 @@ # This Travis job script has been generated by a script via # # runghc make_travis_yml_2.hs '-o' '.travis.yml' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-installed' 'cabal.project' # # For more information, see https://github.com/hvr/multi-ghc-travis # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage addons: apt: packages: &apt_packages - ghc-ppa-tools - alex-3.1.4 - happy-1.19.5 matrix: include: - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.2.2], sources: [hvr-ghc]}} - - compiler: "ghc-8.4.1" + - compiler: "ghc-8.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks - addons: {apt: {packages: [*apt_packages,cabal-install-2.2,ghc-8.4.1], sources: [hvr-ghc]}} + addons: {apt: {packages: [*apt_packages,cabal-install-2.2,ghc-8.4.2], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [*apt_packages,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" - compiler: "ghc-head" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - INSTALLED=${INSTALLED-true} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i.bak 's/-- allow-newer:.*/allow-newer: *:base, *:template-haskell, *:ghc, *:Cabal/' ${HOME}/.cabal/config echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - cat cabal.project - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf "."/.ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - (cd "." && cabal sdist) - mv "."/dist/tagged-*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - cat cabal.project # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - rm -rf ./dist-newstyle - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi # REGENDATA ["-o",".travis.yml","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-installed","cabal.project"] # EOF diff --git a/tagged.cabal b/tagged.cabal index fbac1e9..f40f619 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,76 +1,76 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 - , GHC == 8.4.1 + , GHC == 8.4.2 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.14 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6, transformers-compat >= 0.5 && < 1
ekmett/tagged
155a6af08a77acc5f6931483a201f8c5c3cd7e0f
Fully enable GHC 8.4.1 on Travis
diff --git a/.travis.yml b/.travis.yml index 854e4d0..c7be4b6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,153 +1,152 @@ # This Travis job script has been generated by a script via # # runghc make_travis_yml_2.hs '-o' '.travis.yml' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-installed' 'cabal.project' # # For more information, see https://github.com/hvr/multi-ghc-travis # language: c sudo: false git: submodules: false # whether to recursively clone submodules notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update' - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx - rm -rfv $HOME/.cabal/packages/head.hackage addons: apt: packages: &apt_packages - ghc-ppa-tools - alex-3.1.4 - happy-1.19.5 matrix: include: - compiler: "ghc-7.0.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.0.4], sources: [hvr-ghc]}} - compiler: "ghc-7.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.2.2], sources: [hvr-ghc]}} - compiler: "ghc-7.4.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.4.2], sources: [hvr-ghc]}} - compiler: "ghc-7.6.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.6.3], sources: [hvr-ghc]}} - compiler: "ghc-7.8.4" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.8.4], sources: [hvr-ghc]}} - compiler: "ghc-7.10.3" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.10.3], sources: [hvr-ghc]}} - compiler: "ghc-8.0.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.0.2], sources: [hvr-ghc]}} - compiler: "ghc-8.2.2" # env: TEST=--disable-tests BENCH=--disable-benchmarks addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.2.2], sources: [hvr-ghc]}} - compiler: "ghc-8.4.1" - env: GHCHEAD=true - addons: {apt: {packages: [*apt_packages,cabal-install-head,ghc-8.4.1], sources: [hvr-ghc]}} + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.2,ghc-8.4.1], sources: [hvr-ghc]}} - compiler: "ghc-head" env: GHCHEAD=true addons: {apt: {packages: [*apt_packages,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - compiler: "ghc-7.0.4" - compiler: "ghc-7.2.2" - - compiler: "ghc-8.4.1" - compiler: "ghc-head" before_install: - HC=${CC} - HCPKG=${HC/ghc/ghc-pkg} - unset CC - ROOTDIR=$(pwd) - mkdir -p $HOME/.local/bin - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER install: - cabal --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" - BENCH=${BENCH---enable-benchmarks} - TEST=${TEST---enable-tests} - HADDOCK=${HADDOCK-true} - INSTALLED=${INSTALLED-true} - GHCHEAD=${GHCHEAD-false} - travis_retry cabal update -v - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" - rm -fv cabal.project cabal.project.local # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage - | if $GHCHEAD; then sed -i.bak 's/-- allow-newer:.*/allow-newer: *:base, *:template-haskell, *:ghc, *:Cabal/' ${HOME}/.cabal/config echo 'repository head.hackage' >> ${HOME}/.cabal/config echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config echo ' secure: True' >> ${HOME}/.cabal/config echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config echo ' key-threshold: 3' >> ${HOME}/.cabal.config cabal new-update head.hackage -v fi - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' - "printf 'packages: \".\"\\n' > cabal.project" - cat cabal.project - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi - rm -f cabal.project.freeze - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all - rm -rf "."/.ghc.environment.* "."/dist - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: # test that source-distributions can be generated - (cd "." && cabal sdist) - mv "."/dist/tagged-*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" - cat cabal.project # build & run tests, build benchmarks - cabal new-build -w ${HC} ${TEST} ${BENCH} all # cabal check - (cd tagged-* && cabal check) # haddock - rm -rf ./dist-newstyle - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi # REGENDATA ["-o",".travis.yml","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-installed","cabal.project"] # EOF
ekmett/tagged
d86a2109773bd79adecf78ed49f85316ff0ae2ad
Bumped upper version bound for template-haskell. (#42)
diff --git a/tagged.cabal b/tagged.cabal index 3870051..fbac1e9 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,76 +1,76 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs tested-with: GHC == 7.0.4 , GHC == 7.2.2 , GHC == 7.4.2 , GHC == 7.6.3 , GHC == 7.8.4 , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2 , GHC == 8.4.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.13 + build-depends: template-haskell >= 2.8 && < 2.14 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6, transformers-compat >= 0.5 && < 1
ekmett/tagged
d3628bb5b7f6403c84df5bd65f88d982cac9de9a
Upgrade multi-ghc-travis setup
diff --git a/.gitignore b/.gitignore index 680208e..cf135d9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,32 @@ dist/ .hsenv/ docs wiki TAGS tags wip .DS_Store .*.swp .*.swo *.o *.hi *~ *# +.stack-work/ +cabal-dev +*.chi +*.chs.h +*.dyn_o +*.dyn_hi +.hpc +.hsenv +.cabal-sandbox/ +cabal.sandbox.config +*.prof +*.aux +*.hp +*.eventlog +cabal.project.local +cabal.project.local~ +.HTF/ +.ghc.environment.* diff --git a/.travis.yml b/.travis.yml index d952dcb..854e4d0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,145 +1,153 @@ -# This file has been generated -- see https://github.com/hvr/multi-ghc-travis +# This Travis job script has been generated by a script via +# +# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-installed' 'cabal.project' +# +# For more information, see https://github.com/hvr/multi-ghc-travis +# language: c sudo: false +git: + submodules: false # whether to recursively clone submodules + +notifications: + irc: + channels: + - "irc.freenode.org#haskell-lens" + skip_join: true + template: + - "\x0313tagged\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}" + cache: directories: - - $HOME/.cabsnap - $HOME/.cabal/packages - - $HOME/.stack + - $HOME/.cabal/store before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log - - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.tar + # remove files that are regenerated by 'cabal update' + - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.* + - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json + - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache + - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar + - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx + + - rm -rfv $HOME/.cabal/packages/head.hackage + +addons: + apt: + packages: &apt_packages + - ghc-ppa-tools + - alex-3.1.4 + - happy-1.19.5 matrix: include: - - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal - compiler: ": #GHC 7.0.4" - addons: {apt: {packages: [cabal-install-1.16,ghc-7.0.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal - compiler: ": #GHC 7.2.2" - addons: {apt: {packages: [cabal-install-1.16,ghc-7.2.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=1.16 GHCVER=7.4.2 BUILD=cabal - compiler: ": #GHC 7.4.2" - addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=1.16 GHCVER=7.6.3 BUILD=cabal - compiler: ": #GHC 7.6.3" - addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=1.18 GHCVER=7.8.4 BUILD=cabal - compiler: ": #GHC 7.8.4" - addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - -# - env: BUILD=stack STACK_YAML=stack-7.8.yaml STACK_OPTIONS=--skip-ghc-check -# compiler: ": #GHC 7.8.4" -# addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - -# - env: BUILD=stack STACK_YAML=stack-7.8.yaml -# os: osx - -# - env: BUILD=stack STACK_OPTIONS=--skip-ghc-check -# compiler: ": #GHC 7.10.1" -# addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=1.22 GHCVER=7.10.3 BUILD=cabal - compiler: ": #GHC 7.10.3" - addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=1.24 GHCVER=8.0.2 BUILD=cabal - compiler: ": #GHC 8.0.2" - addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=2.0 GHCVER=8.2.2 - compiler: ": #GHC 8.2.2" - addons: {apt: {packages: [cabal-install-2.0,ghc-8.2.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - - env: CABALVER=head GHCVER=head BUILD=cabal - compiler: ": #GHC head" - addons: {apt: {packages: [cabal-install-head,ghc-head,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - -# - env: BUILD=stack -# os: osx + - compiler: "ghc-7.0.4" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.0.4], sources: [hvr-ghc]}} + - compiler: "ghc-7.2.2" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.2.2], sources: [hvr-ghc]}} + - compiler: "ghc-7.4.2" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.4.2], sources: [hvr-ghc]}} + - compiler: "ghc-7.6.3" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.6.3], sources: [hvr-ghc]}} + - compiler: "ghc-7.8.4" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.8.4], sources: [hvr-ghc]}} + - compiler: "ghc-7.10.3" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-7.10.3], sources: [hvr-ghc]}} + - compiler: "ghc-8.0.2" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.0.2], sources: [hvr-ghc]}} + - compiler: "ghc-8.2.2" + # env: TEST=--disable-tests BENCH=--disable-benchmarks + addons: {apt: {packages: [*apt_packages,cabal-install-2.0,ghc-8.2.2], sources: [hvr-ghc]}} + - compiler: "ghc-8.4.1" + env: GHCHEAD=true + addons: {apt: {packages: [*apt_packages,cabal-install-head,ghc-8.4.1], sources: [hvr-ghc]}} + - compiler: "ghc-head" + env: GHCHEAD=true + addons: {apt: {packages: [*apt_packages,cabal-install-head,ghc-head], sources: [hvr-ghc]}} allow_failures: - - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal - - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal - - env: CABALVER=head GHCVER=head BUILD=cabal + - compiler: "ghc-7.0.4" + - compiler: "ghc-7.2.2" + - compiler: "ghc-8.4.1" + - compiler: "ghc-head" before_install: - - unset CC - - case "$BUILD" in - stack) - export STACK_VERSION=0.1.3.0; - mkdir -p ~/bin; - travis_retry curl -L https://github.com/commercialhaskell/stack/releases/download/v$STACK_VERSION/stack-$STACK_VERSION-x86_64-$TRAVIS_OS_NAME.gz | gunzip > ~/bin/stack; - chmod a+x ~/bin/stack; - scripts/travis_long stack --no-terminal setup; - export PATH=~/bin:$PATH;; - cabal) - export HAPPYVER=1.19.5 - export ALEXVER=3.1.4 - export PATH=~/.cabal/bin:/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:/opt/happy/$HAPPYVER/bin:/opt/alex/$ALEXVER/bin:$PATH;; - esac + - HC=${CC} + - HCPKG=${HC/ghc/ghc-pkg} + - unset CC + - ROOTDIR=$(pwd) + - mkdir -p $HOME/.local/bin + - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH" + - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) + - echo $HCNUMVER + install: - - case "$BUILD" in - stack) - scripts/travis_long stack --no-terminal $STACK_OPTIONS build --only-snapshot -j2;; - cabal) - echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]" - cabal --version; - if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ]; - then - zcat $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz > - $HOME/.cabal/packages/hackage.haskell.org/00-index.tar; - fi; - travis_retry cabal update; - cabal install --only-dependencies --enable-tests --enable-benchmarks --dry -v > installplan.txt; - sed -i -e '1,/^Resolving /d' installplan.txt; cat installplan.txt; - if diff -u installplan.txt $HOME/.cabsnap/installplan.txt; then - echo "cabal build-cache HIT"; - rm -rfv .ghc; - cp -a $HOME/.cabsnap/ghc $HOME/.ghc; - cp -a $HOME/.cabsnap/lib $HOME/.cabsnap/share $HOME/.cabsnap/bin $HOME/.cabal/; - else - echo "cabal build-cache MISS"; - rm -rf $HOME/.cabsnap; - mkdir -p $HOME/.ghc $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin; - cabal install --only-dependencies --enable-tests --enable-benchmarks; - fi; - if [ ! -d $HOME/.cabsnap ]; then - echo "snapshotting package-db to build-cache"; - mkdir $HOME/.cabsnap; - cp -a $HOME/.ghc $HOME/.cabsnap/ghc; - cp -a $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin installplan.txt $HOME/.cabsnap/; - fi;; - esac - -# snapshot package-db on cache miss + - cabal --version + - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]" + - BENCH=${BENCH---enable-benchmarks} + - TEST=${TEST---enable-tests} + - HADDOCK=${HADDOCK-true} + - INSTALLED=${INSTALLED-true} + - GHCHEAD=${GHCHEAD-false} + - travis_retry cabal update -v + - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config" + - rm -fv cabal.project cabal.project.local + # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage + - | + if $GHCHEAD; then + sed -i.bak 's/-- allow-newer:.*/allow-newer: *:base, *:template-haskell, *:ghc, *:Cabal/' ${HOME}/.cabal/config + + echo 'repository head.hackage' >> ${HOME}/.cabal/config + echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config + echo ' secure: True' >> ${HOME}/.cabal/config + echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config + echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config + echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config + echo ' key-threshold: 3' >> ${HOME}/.cabal.config + + cabal new-update head.hackage -v + fi + - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$' + - "printf 'packages: \".\"\\n' > cabal.project" + - cat cabal.project + - if [ -f "./configure.ac" ]; then + (cd "." && autoreconf -i); + fi + - rm -f cabal.project.freeze + - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all + - rm -rf "."/.ghc.environment.* "."/dist + - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX) # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: - - case "$BUILD" in - stack) - scripts/travis_long stack --no-terminal $STACK_OPTIONS build -j2;; - cabal) - cabal configure --enable-tests -v2; - cabal build; - cabal test; - cabal bench || true; - cabal sdist || true; - SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz && (cd dist && cabal install --force-reinstalls "$SRC_TGZ");; - esac + # test that source-distributions can be generated + - (cd "." && cabal sdist) + - mv "."/dist/tagged-*.tar.gz ${DISTDIR}/ + - cd ${DISTDIR} || false + - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \; + - "printf 'packages: tagged-*/*.cabal\\n' > cabal.project" + - cat cabal.project -notifications: - irc: - channels: - - "irc.freenode.org#haskell-lens" - skip_join: true - template: - - "\x0313tagged\x0f/\x0306%{branch}\x0f \x0314%{commit}\x0f %{message} \x0302\x1f%{build_url}\x0f" + + # build & run tests, build benchmarks + - cabal new-build -w ${HC} ${TEST} ${BENCH} all + + # cabal check + - (cd tagged-* && cabal check) + + # haddock + - rm -rf ./dist-newstyle + - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi + +# REGENDATA ["-o",".travis.yml","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-installed","cabal.project"] # EOF diff --git a/cabal.project b/cabal.project new file mode 100644 index 0000000..e6fdbad --- /dev/null +++ b/cabal.project @@ -0,0 +1 @@ +packages: . diff --git a/tagged.cabal b/tagged.cabal index 8eb3849..3870051 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,67 +1,76 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett -description: Haskell 98 phantom types to avoid unsafely passing dummy arguments +description: Haskell 98 phantom types to avoid unsafely passing dummy arguments. build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs +tested-with: GHC == 7.0.4 + , GHC == 7.2.2 + , GHC == 7.4.2 + , GHC == 7.6.3 + , GHC == 7.8.4 + , GHC == 7.10.3 + , GHC == 8.0.2 + , GHC == 8.2.2 + , GHC == 8.4.1 source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH build-depends: template-haskell >= 2.8 && < 2.13 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6, transformers-compat >= 0.5 && < 1
ekmett/tagged
2f40dfa9881e702a652cee0c4fd45ae23c80c4df
Use GHC 8.2.2 on Travis
diff --git a/.travis.yml b/.travis.yml index ecca9e9..d952dcb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,145 +1,145 @@ # This file has been generated -- see https://github.com/hvr/multi-ghc-travis language: c sudo: false cache: directories: - $HOME/.cabsnap - $HOME/.cabal/packages - $HOME/.stack before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.tar matrix: include: - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal compiler: ": #GHC 7.0.4" addons: {apt: {packages: [cabal-install-1.16,ghc-7.0.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal compiler: ": #GHC 7.2.2" addons: {apt: {packages: [cabal-install-1.16,ghc-7.2.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.4.2 BUILD=cabal compiler: ": #GHC 7.4.2" addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.6.3 BUILD=cabal compiler: ": #GHC 7.6.3" addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.18 GHCVER=7.8.4 BUILD=cabal compiler: ": #GHC 7.8.4" addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack STACK_YAML=stack-7.8.yaml STACK_OPTIONS=--skip-ghc-check # compiler: ": #GHC 7.8.4" # addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack STACK_YAML=stack-7.8.yaml # os: osx # - env: BUILD=stack STACK_OPTIONS=--skip-ghc-check # compiler: ": #GHC 7.10.1" # addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.22 GHCVER=7.10.3 BUILD=cabal compiler: ": #GHC 7.10.3" addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.24 GHCVER=8.0.2 BUILD=cabal compiler: ": #GHC 8.0.2" addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - - env: CABALVER=2.0 GHCVER=8.2.1 - compiler: ": #GHC 8.2.1" - addons: {apt: {packages: [cabal-install-2.0,ghc-8.2.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + - env: CABALVER=2.0 GHCVER=8.2.2 + compiler: ": #GHC 8.2.2" + addons: {apt: {packages: [cabal-install-2.0,ghc-8.2.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=head GHCVER=head BUILD=cabal compiler: ": #GHC head" addons: {apt: {packages: [cabal-install-head,ghc-head,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack # os: osx allow_failures: - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal - env: CABALVER=head GHCVER=head BUILD=cabal before_install: - unset CC - case "$BUILD" in stack) export STACK_VERSION=0.1.3.0; mkdir -p ~/bin; travis_retry curl -L https://github.com/commercialhaskell/stack/releases/download/v$STACK_VERSION/stack-$STACK_VERSION-x86_64-$TRAVIS_OS_NAME.gz | gunzip > ~/bin/stack; chmod a+x ~/bin/stack; scripts/travis_long stack --no-terminal setup; export PATH=~/bin:$PATH;; cabal) export HAPPYVER=1.19.5 export ALEXVER=3.1.4 export PATH=~/.cabal/bin:/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:/opt/happy/$HAPPYVER/bin:/opt/alex/$ALEXVER/bin:$PATH;; esac install: - case "$BUILD" in stack) scripts/travis_long stack --no-terminal $STACK_OPTIONS build --only-snapshot -j2;; cabal) echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]" cabal --version; if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ]; then zcat $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz > $HOME/.cabal/packages/hackage.haskell.org/00-index.tar; fi; travis_retry cabal update; cabal install --only-dependencies --enable-tests --enable-benchmarks --dry -v > installplan.txt; sed -i -e '1,/^Resolving /d' installplan.txt; cat installplan.txt; if diff -u installplan.txt $HOME/.cabsnap/installplan.txt; then echo "cabal build-cache HIT"; rm -rfv .ghc; cp -a $HOME/.cabsnap/ghc $HOME/.ghc; cp -a $HOME/.cabsnap/lib $HOME/.cabsnap/share $HOME/.cabsnap/bin $HOME/.cabal/; else echo "cabal build-cache MISS"; rm -rf $HOME/.cabsnap; mkdir -p $HOME/.ghc $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin; cabal install --only-dependencies --enable-tests --enable-benchmarks; fi; if [ ! -d $HOME/.cabsnap ]; then echo "snapshotting package-db to build-cache"; mkdir $HOME/.cabsnap; cp -a $HOME/.ghc $HOME/.cabsnap/ghc; cp -a $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin installplan.txt $HOME/.cabsnap/; fi;; esac # snapshot package-db on cache miss # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: - case "$BUILD" in stack) scripts/travis_long stack --no-terminal $STACK_OPTIONS build -j2;; cabal) cabal configure --enable-tests -v2; cabal build; cabal test; cabal bench || true; cabal sdist || true; SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz && (cd dist && cabal install --force-reinstalls "$SRC_TGZ");; esac notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x0f/\x0306%{branch}\x0f \x0314%{commit}\x0f %{message} \x0302\x1f%{build_url}\x0f" # EOF
ekmett/tagged
4528944419c8ad685d58ef8ef3bbc010af1a9a3a
Define logBase for Tagged in terms of base type's logBase (#41)
diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs index a681e7c..edd247c 100644 --- a/src/Data/Tagged.hs +++ b/src/Data/Tagged.hs @@ -1,488 +1,488 @@ {-# LANGUAGE CPP #-} #ifdef LANGUAGE_DeriveDataTypeable {-# LANGUAGE DeriveDataTypeable #-} #endif #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE PolyKinds #-} #endif #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE DeriveGeneric #-} #if __GLASGOW_HASKELL__ < 710 {-# LANGUAGE Trustworthy #-} #endif #endif {-# OPTIONS_GHC -fno-warn-deprecations #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Tagged -- Copyright : 2009-2015 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Tagged ( -- * Tagged values Tagged(..) , retag , untag , tagSelf , untagSelf , asTaggedTypeOf , witness -- * Conversion , proxy , unproxy , tagWith -- * Proxy methods GHC dropped , reproxy ) where #if MIN_VERSION_base(4,8,0) import Control.Applicative (liftA2) #else import Control.Applicative ((<$>), liftA2, Applicative(..)) import Data.Traversable (Traversable(..)) import Data.Monoid #endif import Data.Bits import Data.Foldable (Foldable(..)) #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif #ifdef MIN_VERSION_transformers import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) # if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) , Eq2(..), Ord2(..), Read2(..), Show2(..) # endif ) #endif import Control.Monad (liftM) #if MIN_VERSION_base(4,8,0) import Data.Bifunctor #endif #if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) #endif #ifdef __GLASGOW_HASKELL__ import Data.Data #endif import Data.Ix (Ix(..)) #if __GLASGOW_HASKELL__ < 707 import Data.Proxy #endif #if MIN_VERSION_base(4,9,0) import Data.Semigroup (Semigroup(..)) #endif import Data.String (IsString(..)) import Foreign.Ptr (castPtr) import Foreign.Storable (Storable(..)) #if __GLASGOW_HASKELL__ >= 702 import GHC.Generics (Generic) #if __GLASGOW_HASKELL__ >= 706 import GHC.Generics (Generic1) #endif #endif -- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. -- This can be used in place of the more traditional but less safe idiom of -- passing in an undefined value with the type, because unlike an @(s -> b)@, -- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the extra -- argument, because the newtype is \"free\" -- -- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore -- there is an extra @k@ showing in the instance haddocks that may cause confusion. newtype Tagged s b = Tagged { unTagged :: b } deriving ( Eq, Ord, Ix, Bounded #if __GLASGOW_HASKELL__ >= 702 , Generic #if __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #endif #if __GLASGOW_HASKELL__ >= 707 , Typeable #endif ) #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 707 instance Typeable2 Tagged where typeOf2 _ = mkTyConApp taggedTyCon [] taggedTyCon :: TyCon #if __GLASGOW_HASKELL__ < 704 taggedTyCon = mkTyCon "Data.Tagged.Tagged" #else taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged" #endif #endif instance (Data s, Data b) => Data (Tagged s b) where gfoldl f z (Tagged b) = z Tagged `f` b toConstr _ = taggedConstr gunfold k z c = case constrIndex c of 1 -> k (z Tagged) _ -> error "gunfold" dataTypeOf _ = taggedDataType dataCast1 f = gcast1 f dataCast2 f = gcast2 f taggedConstr :: Constr taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix {-# INLINE taggedConstr #-} taggedDataType :: DataType taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] {-# INLINE taggedDataType #-} #endif instance Show b => Show (Tagged s b) where showsPrec n (Tagged b) = showParen (n > 10) $ showString "Tagged " . showsPrec 11 b instance Read b => Read (Tagged s b) where readsPrec d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] #if MIN_VERSION_base(4,9,0) instance Semigroup a => Semigroup (Tagged s a) where Tagged a <> Tagged b = Tagged (a <> b) stimes n (Tagged a) = Tagged (stimes n a) instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where mempty = Tagged mempty mappend = (<>) #else instance Monoid a => Monoid (Tagged s a) where mempty = Tagged mempty mappend (Tagged a) (Tagged b) = Tagged (mappend a b) #endif instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} #if MIN_VERSION_base(4,8,0) -- this instance is provided by the bifunctors package for GHC<7.9 instance Bifunctor Tagged where bimap _ g (Tagged b) = Tagged (g b) {-# INLINE bimap #-} #endif #if MIN_VERSION_base(4,10,0) -- these instances are provided by the bifunctors package for GHC<8.1 instance Bifoldable Tagged where bifoldMap _ g (Tagged b) = g b {-# INLINE bifoldMap #-} instance Bitraversable Tagged where bitraverse _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse #-} #endif #ifdef MIN_VERSION_deepseq instance NFData b => NFData (Tagged s b) where rnf (Tagged b) = rnf b #endif #ifdef MIN_VERSION_transformers # if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) instance Eq1 (Tagged s) where eq1 = (==) instance Ord1 (Tagged s) where compare1 = compare instance Read1 (Tagged s) where readsPrec1 = readsPrec instance Show1 (Tagged s) where showsPrec1 = showsPrec # else instance Eq1 (Tagged s) where liftEq eq (Tagged a) (Tagged b) = eq a b instance Ord1 (Tagged s) where liftCompare cmp (Tagged a) (Tagged b) = cmp a b instance Read1 (Tagged s) where liftReadsPrec rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show1 (Tagged s) where liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b instance Eq2 Tagged where liftEq2 _ eq (Tagged a) (Tagged b) = eq a b instance Ord2 Tagged where liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b instance Read2 Tagged where liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show2 Tagged where liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b # endif #endif instance Applicative (Tagged s) where pure = Tagged {-# INLINE pure #-} Tagged f <*> Tagged x = Tagged (f x) {-# INLINE (<*>) #-} _ *> n = n {-# INLINE (*>) #-} instance Monad (Tagged s) where return = pure {-# INLINE return #-} Tagged m >>= k = k m {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Foldable (Tagged s) where foldMap f (Tagged x) = f x {-# INLINE foldMap #-} fold (Tagged x) = x {-# INLINE fold #-} foldr f z (Tagged x) = f x z {-# INLINE foldr #-} foldl f z (Tagged x) = f z x {-# INLINE foldl #-} foldl1 _ (Tagged x) = x {-# INLINE foldl1 #-} foldr1 _ (Tagged x) = x {-# INLINE foldr1 #-} instance Traversable (Tagged s) where traverse f (Tagged x) = Tagged <$> f x {-# INLINE traverse #-} sequenceA (Tagged x) = Tagged <$> x {-# INLINE sequenceA #-} mapM f (Tagged x) = liftM Tagged (f x) {-# INLINE mapM #-} sequence (Tagged x) = liftM Tagged x {-# INLINE sequence #-} instance Enum a => Enum (Tagged s a) where succ = fmap succ pred = fmap pred toEnum = Tagged . toEnum fromEnum (Tagged x) = fromEnum x enumFrom (Tagged x) = map Tagged (enumFrom x) enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = map Tagged (enumFromThenTo x y z) instance Num a => Num (Tagged s a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = Tagged . fromInteger instance Real a => Real (Tagged s a) where toRational (Tagged x) = toRational x instance Integral a => Integral (Tagged s a) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = quotRem x y divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = divMod x y toInteger (Tagged x) = toInteger x instance Fractional a => Fractional (Tagged s a) where (/) = liftA2 (/) recip = fmap recip fromRational = Tagged . fromRational instance Floating a => Floating (Tagged s a) where pi = Tagged pi exp = fmap exp log = fmap log sqrt = fmap sqrt sin = fmap sin cos = fmap cos tan = fmap tan asin = fmap asin acos = fmap acos atan = fmap atan sinh = fmap sinh cosh = fmap cosh tanh = fmap tanh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh (**) = liftA2 (**) - logBase = liftA2 (**) + logBase = liftA2 logBase instance RealFrac a => RealFrac (Tagged s a) where properFraction (Tagged x) = (a, Tagged b) where (a, b) = properFraction x truncate (Tagged x) = truncate x round (Tagged x) = round x ceiling (Tagged x) = ceiling x floor (Tagged x) = floor x instance RealFloat a => RealFloat (Tagged s a) where floatRadix (Tagged x) = floatRadix x floatDigits (Tagged x) = floatDigits x floatRange (Tagged x) = floatRange x decodeFloat (Tagged x) = decodeFloat x encodeFloat m n = Tagged (encodeFloat m n) exponent (Tagged x) = exponent x significand = fmap significand scaleFloat n = fmap (scaleFloat n) isNaN (Tagged x) = isNaN x isInfinite (Tagged x) = isInfinite x isDenormalized (Tagged x) = isDenormalized x isNegativeZero (Tagged x) = isNegativeZero x isIEEE (Tagged x) = isIEEE x atan2 = liftA2 atan2 instance Bits a => Bits (Tagged s a) where Tagged a .&. Tagged b = Tagged (a .&. b) Tagged a .|. Tagged b = Tagged (a .|. b) xor (Tagged a) (Tagged b) = Tagged (xor a b) complement (Tagged a) = Tagged (complement a) shift (Tagged a) i = Tagged (shift a i) shiftL (Tagged a) i = Tagged (shiftL a i) shiftR (Tagged a) i = Tagged (shiftR a i) rotate (Tagged a) i = Tagged (rotate a i) rotateL (Tagged a) i = Tagged (rotateL a i) rotateR (Tagged a) i = Tagged (rotateR a i) bit i = Tagged (bit i) setBit (Tagged a) i = Tagged (setBit a i) clearBit (Tagged a) i = Tagged (clearBit a i) complementBit (Tagged a) i = Tagged (complementBit a i) testBit (Tagged a) i = testBit a i isSigned (Tagged a) = isSigned a bitSize (Tagged a) = bitSize a -- deprecated, but still required :( #if MIN_VERSION_base(4,5,0) unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) popCount (Tagged a) = popCount a #endif #if MIN_VERSION_base(4,7,0) bitSizeMaybe (Tagged a) = bitSizeMaybe a zeroBits = Tagged zeroBits #endif #if MIN_VERSION_base(4,7,0) instance FiniteBits a => FiniteBits (Tagged s a) where finiteBitSize (Tagged a) = finiteBitSize a # if MIN_VERSION_base(4,8,0) countLeadingZeros (Tagged a) = countLeadingZeros a countTrailingZeros (Tagged a) = countTrailingZeros a # endif #endif instance IsString a => IsString (Tagged s a) where fromString = Tagged . fromString instance Storable a => Storable (Tagged s a) where sizeOf t = sizeOf a where Tagged a = Tagged undefined `asTypeOf` t alignment t = alignment a where Tagged a = Tagged undefined `asTypeOf` t peek ptr = Tagged <$> peek (castPtr ptr) poke ptr (Tagged a) = poke (castPtr ptr) a peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a -- | Some times you need to change the tag you have lying around. -- Idiomatic usage is to make a new combinator for the relationship between the -- tags that you want to enforce, and define that combinator using 'retag'. -- -- @ -- data Succ n -- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a -- retagSucc = 'retag' -- @ retag :: Tagged s b -> Tagged t b retag = Tagged . unTagged {-# INLINE retag #-} -- | Alias for 'unTagged' untag :: Tagged s b -> b untag = unTagged -- | Tag a value with its own type. tagSelf :: a -> Tagged a a tagSelf = Tagged {-# INLINE tagSelf #-} -- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. asTaggedTypeOf :: s -> tagged s b -> s asTaggedTypeOf = const {-# INLINE asTaggedTypeOf #-} witness :: Tagged a b -> a -> b witness (Tagged b) _ = b {-# INLINE witness #-} -- | 'untagSelf' is a type-restricted version of 'untag'. untagSelf :: Tagged a a -> a untagSelf (Tagged x) = x {-# INLINE untagSelf #-} -- | Convert from a 'Tagged' representation to a representation -- based on a 'Proxy'. proxy :: Tagged s a -> proxy s -> a proxy (Tagged x) _ = x {-# INLINE proxy #-} -- | Convert from a representation based on a 'Proxy' to a 'Tagged' -- representation. unproxy :: (Proxy s -> a) -> Tagged s a unproxy f = Tagged (f Proxy) {-# INLINE unproxy #-} -- | Another way to convert a proxy to a tag. tagWith :: proxy s -> a -> Tagged s a tagWith _ = Tagged {-# INLINE tagWith #-} -- | Some times you need to change the proxy you have lying around. -- Idiomatic usage is to make a new combinator for the relationship -- between the proxies that you want to enforce, and define that -- combinator using 'reproxy'. -- -- @ -- data Succ n -- reproxySucc :: proxy n -> 'Proxy' (Succ n) -- reproxySucc = 'reproxy' -- @ reproxy :: proxy a -> Proxy b reproxy _ = Proxy
ekmett/tagged
1515a70884f1631624c81bcba3240ddf8cf77ece
Make the Read(1) instance for Proxy ignore precedence
diff --git a/old/Data/Proxy.hs b/old/Data/Proxy.hs index 3cce748..b6a4951 100644 --- a/old/Data/Proxy.hs +++ b/old/Data/Proxy.hs @@ -1,279 +1,279 @@ {-# LANGUAGE CPP #-} #ifdef LANGUAGE_DeriveDataTypeable {-# LANGUAGE DeriveDataTypeable #-} #endif #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE KindSignatures #-} {-# LANGUAGE PolyKinds #-} #endif #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE StandaloneDeriving #-} #endif #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TypeFamilies #-} #endif {-# OPTIONS_GHC -fno-warn-orphans #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Proxy -- Copyright : 2009-2013 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Proxy ( -- * Proxy values Proxy(..) , asProxyTypeOf , KProxy(..) ) where import Control.Applicative (Applicative(..), Alternative(..)) import Control.Monad (MonadPlus(..)) #if MIN_VERSION_base(4,4,0) import Control.Monad.Zip (MonadZip(..)) #endif #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif #ifdef MIN_VERSION_transformers import Data.Functor.Classes (Eq1(..), Ord1(..), Read1(..), Show1(..)) #endif import Data.Traversable (Traversable(..)) import Data.Foldable (Foldable(..)) import Data.Ix (Ix(..)) import Data.Monoid #ifdef __GLASGOW_HASKELL__ import GHC.Arr (unsafeIndex, unsafeRangeSize) import Data.Data #if __GLASGOW_HASKELL__ >= 702 import GHC.Generics hiding (Fixity(..)) #endif #endif #if __GLASGOW_HASKELL__ >= 707 deriving instance Typeable Proxy #else data Proxy s = Proxy #if __GLASGOW_HASKELL__ >= 702 deriving Generic -- We have to implement the Generic1 instance manually due to an old -- bug in GHC 7.6. This is mostly copied from the output of -- -- deriving instance Generic1 Proxy -- -- Compiled with -ddump-deriv on a more recent GHC. instance Generic1 Proxy where type Rep1 Proxy = D1 ProxyMetaData (C1 ProxyMetaCons U1) from1 Proxy = M1 (M1 U1) to1 (M1 (M1 U1)) = Proxy data ProxyMetaData data ProxyMetaCons instance Datatype ProxyMetaData where datatypeName _ = "Proxy" moduleName _ = "Data.Proxy" instance Constructor ProxyMetaCons where conName _ = "Proxy" #endif #endif instance Eq (Proxy s) where _ == _ = True instance Ord (Proxy s) where compare _ _ = EQ instance Show (Proxy s) where showsPrec _ _ = showString "Proxy" instance Read (Proxy s) where - readsPrec d = readParen (d > 10) (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) + readsPrec _ = readParen False (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 707 instance Typeable1 Proxy where typeOf1 _ = mkTyConApp proxyTyCon [] proxyTyCon :: TyCon #if __GLASGOW_HASKELL__ < 704 proxyTyCon = mkTyCon "Data.Proxy.Proxy" #else proxyTyCon = mkTyCon3 "tagged" "Data.Proxy" "Proxy" #endif {-# NOINLINE proxyTyCon #-} #endif instance Data s => Data (Proxy s) where gfoldl _ z _ = z Proxy toConstr _ = proxyConstr gunfold _ z c = case constrIndex c of 1 -> z Proxy _ -> error "gunfold" dataTypeOf _ = proxyDataType dataCast1 f = gcast1 f proxyConstr :: Constr proxyConstr = mkConstr proxyDataType "Proxy" [] Prefix {-# NOINLINE proxyConstr #-} proxyDataType :: DataType proxyDataType = mkDataType "Data.Proxy.Proxy" [proxyConstr] {-# NOINLINE proxyDataType #-} #endif instance Enum (Proxy s) where succ _ = error "Proxy.succ" pred _ = error "Proxy.pred" fromEnum _ = 0 toEnum 0 = Proxy toEnum _ = error "Proxy.toEnum: 0 expected" enumFrom _ = [Proxy] enumFromThen _ _ = [Proxy] enumFromThenTo _ _ _ = [Proxy] enumFromTo _ _ = [Proxy] instance Ix (Proxy s) where range _ = [Proxy] index _ _ = 0 inRange _ _ = True rangeSize _ = 1 #ifdef __GLASGOW_HASKELL__ unsafeIndex _ _ = 0 unsafeRangeSize _ = 1 #endif instance Bounded (Proxy s) where minBound = Proxy maxBound = Proxy #ifdef MIN_VERSION_deepseq instance NFData (Proxy s) where rnf Proxy = () #endif #ifdef MIN_VERSION_transformers # if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) instance Eq1 Proxy where eq1 = (==) instance Ord1 Proxy where compare1 = compare instance Read1 Proxy where readsPrec1 = readsPrec instance Show1 Proxy where showsPrec1 = showsPrec # else instance Eq1 Proxy where liftEq _ _ _ = True instance Ord1 Proxy where liftCompare _ _ _ = EQ instance Show1 Proxy where liftShowsPrec _ _ _ _ = showString "Proxy" instance Read1 Proxy where - liftReadsPrec _ _ d = - readParen (d > 10) (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) + liftReadsPrec _ _ _ = + readParen False (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) # endif #endif instance Functor Proxy where fmap _ _ = Proxy {-# INLINE fmap #-} instance Applicative Proxy where pure _ = Proxy {-# INLINE pure #-} _ <*> _ = Proxy {-# INLINE (<*>) #-} instance Alternative Proxy where empty = Proxy {-# INLINE empty #-} _ <|> _ = Proxy {-# INLINE (<|>) #-} instance Monoid (Proxy s) where mempty = Proxy {-# INLINE mempty #-} mappend _ _ = Proxy {-# INLINE mappend #-} mconcat _ = Proxy {-# INLINE mconcat #-} instance Monad Proxy where return _ = Proxy {-# INLINE return #-} _ >>= _ = Proxy {-# INLINE (>>=) #-} instance MonadPlus Proxy where mzero = Proxy {-# INLINE mzero #-} mplus _ _ = Proxy {-# INLINE mplus #-} #if MIN_VERSION_base(4,4,0) instance MonadZip Proxy where mzipWith _ _ _ = Proxy {-# INLINE mzipWith #-} #endif instance Foldable Proxy where foldMap _ _ = mempty {-# INLINE foldMap #-} fold _ = mempty {-# INLINE fold #-} foldr _ z _ = z {-# INLINE foldr #-} foldl _ z _ = z {-# INLINE foldl #-} foldl1 _ _ = error "foldl1: Proxy" {-# INLINE foldl1 #-} foldr1 _ _ = error "foldr1: Proxy" {-# INLINE foldr1 #-} instance Traversable Proxy where traverse _ _ = pure Proxy {-# INLINE traverse #-} sequenceA _ = pure Proxy {-# INLINE sequenceA #-} mapM _ _ = return Proxy {-# INLINE mapM #-} sequence _ = return Proxy {-# INLINE sequence #-} -- | 'asProxyTypeOf' is a type-restricted version of 'const'. -- It is usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the tag -- of the second. asProxyTypeOf :: a -> proxy a -> a asProxyTypeOf = const {-# INLINE asProxyTypeOf #-} -- | A concrete, promotable proxy type, for use at the kind level -- There are no instances for this because it is intended at the kind level only data KProxy #if __GLASGOW_HASKELL__ >= 706 (t :: *) #else t #endif = KProxy #if defined(LANGUAGE_DeriveDataTypeable) deriving Typeable #endif
ekmett/tagged
f422376936c75c130d116f4cf9ecbebcd949fa6f
Add GHC 8.2.1 Travis build
diff --git a/.travis.yml b/.travis.yml index 007f4fa..ecca9e9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,141 +1,145 @@ # This file has been generated -- see https://github.com/hvr/multi-ghc-travis language: c sudo: false cache: directories: - $HOME/.cabsnap - $HOME/.cabal/packages - $HOME/.stack before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.tar matrix: include: - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal compiler: ": #GHC 7.0.4" addons: {apt: {packages: [cabal-install-1.16,ghc-7.0.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal compiler: ": #GHC 7.2.2" addons: {apt: {packages: [cabal-install-1.16,ghc-7.2.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.4.2 BUILD=cabal compiler: ": #GHC 7.4.2" addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.6.3 BUILD=cabal compiler: ": #GHC 7.6.3" addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.18 GHCVER=7.8.4 BUILD=cabal compiler: ": #GHC 7.8.4" addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack STACK_YAML=stack-7.8.yaml STACK_OPTIONS=--skip-ghc-check # compiler: ": #GHC 7.8.4" # addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack STACK_YAML=stack-7.8.yaml # os: osx # - env: BUILD=stack STACK_OPTIONS=--skip-ghc-check # compiler: ": #GHC 7.10.1" # addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.22 GHCVER=7.10.3 BUILD=cabal compiler: ": #GHC 7.10.3" addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.24 GHCVER=8.0.2 BUILD=cabal compiler: ": #GHC 8.0.2" addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + - env: CABALVER=2.0 GHCVER=8.2.1 + compiler: ": #GHC 8.2.1" + addons: {apt: {packages: [cabal-install-2.0,ghc-8.2.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + - env: CABALVER=head GHCVER=head BUILD=cabal compiler: ": #GHC head" addons: {apt: {packages: [cabal-install-head,ghc-head,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack # os: osx allow_failures: - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal - env: CABALVER=head GHCVER=head BUILD=cabal before_install: - unset CC - case "$BUILD" in stack) export STACK_VERSION=0.1.3.0; mkdir -p ~/bin; travis_retry curl -L https://github.com/commercialhaskell/stack/releases/download/v$STACK_VERSION/stack-$STACK_VERSION-x86_64-$TRAVIS_OS_NAME.gz | gunzip > ~/bin/stack; chmod a+x ~/bin/stack; scripts/travis_long stack --no-terminal setup; export PATH=~/bin:$PATH;; cabal) export HAPPYVER=1.19.5 export ALEXVER=3.1.4 export PATH=~/.cabal/bin:/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:/opt/happy/$HAPPYVER/bin:/opt/alex/$ALEXVER/bin:$PATH;; esac install: - case "$BUILD" in stack) scripts/travis_long stack --no-terminal $STACK_OPTIONS build --only-snapshot -j2;; cabal) echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]" cabal --version; if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ]; then zcat $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz > $HOME/.cabal/packages/hackage.haskell.org/00-index.tar; fi; travis_retry cabal update; cabal install --only-dependencies --enable-tests --enable-benchmarks --dry -v > installplan.txt; sed -i -e '1,/^Resolving /d' installplan.txt; cat installplan.txt; if diff -u installplan.txt $HOME/.cabsnap/installplan.txt; then echo "cabal build-cache HIT"; rm -rfv .ghc; cp -a $HOME/.cabsnap/ghc $HOME/.ghc; cp -a $HOME/.cabsnap/lib $HOME/.cabsnap/share $HOME/.cabsnap/bin $HOME/.cabal/; else echo "cabal build-cache MISS"; rm -rf $HOME/.cabsnap; mkdir -p $HOME/.ghc $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin; cabal install --only-dependencies --enable-tests --enable-benchmarks; fi; if [ ! -d $HOME/.cabsnap ]; then echo "snapshotting package-db to build-cache"; mkdir $HOME/.cabsnap; cp -a $HOME/.ghc $HOME/.cabsnap/ghc; cp -a $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin installplan.txt $HOME/.cabsnap/; fi;; esac # snapshot package-db on cache miss # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: - case "$BUILD" in stack) scripts/travis_long stack --no-terminal $STACK_OPTIONS build -j2;; cabal) cabal configure --enable-tests -v2; cabal build; cabal test; cabal bench || true; cabal sdist || true; SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz && (cd dist && cabal install --force-reinstalls "$SRC_TGZ");; esac notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x0f/\x0306%{branch}\x0f \x0314%{commit}\x0f %{message} \x0302\x1f%{build_url}\x0f" # EOF
ekmett/tagged
298215be7d20177194dc3b1f39498b29ecd97814
Replace some __GLASGOW_HASKELL__s with MIN_VERSION_base
diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs index 3a91f00..a681e7c 100644 --- a/src/Data/Tagged.hs +++ b/src/Data/Tagged.hs @@ -1,488 +1,488 @@ {-# LANGUAGE CPP #-} #ifdef LANGUAGE_DeriveDataTypeable {-# LANGUAGE DeriveDataTypeable #-} #endif #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE PolyKinds #-} #endif #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE DeriveGeneric #-} #if __GLASGOW_HASKELL__ < 710 {-# LANGUAGE Trustworthy #-} #endif #endif {-# OPTIONS_GHC -fno-warn-deprecations #-} ---------------------------------------------------------------------------- -- | -- Module : Data.Tagged -- Copyright : 2009-2015 Edward Kmett -- License : BSD3 -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Data.Tagged ( -- * Tagged values Tagged(..) , retag , untag , tagSelf , untagSelf , asTaggedTypeOf , witness -- * Conversion , proxy , unproxy , tagWith -- * Proxy methods GHC dropped , reproxy ) where -#if __GLASGOW_HASKELL__ >= 710 +#if MIN_VERSION_base(4,8,0) import Control.Applicative (liftA2) #else import Control.Applicative ((<$>), liftA2, Applicative(..)) import Data.Traversable (Traversable(..)) import Data.Monoid #endif import Data.Bits import Data.Foldable (Foldable(..)) #ifdef MIN_VERSION_deepseq import Control.DeepSeq (NFData(..)) #endif #ifdef MIN_VERSION_transformers import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) # if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) , Eq2(..), Ord2(..), Read2(..), Show2(..) # endif ) #endif import Control.Monad (liftM) -#if __GLASGOW_HASKELL__ >= 709 +#if MIN_VERSION_base(4,8,0) import Data.Bifunctor #endif -#if __GLASGOW_HASKELL__ >= 801 +#if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable(..)) import Data.Bitraversable (Bitraversable(..)) #endif #ifdef __GLASGOW_HASKELL__ import Data.Data #endif import Data.Ix (Ix(..)) #if __GLASGOW_HASKELL__ < 707 import Data.Proxy #endif -#if __GLASGOW_HASKELL__ >= 800 +#if MIN_VERSION_base(4,9,0) import Data.Semigroup (Semigroup(..)) #endif import Data.String (IsString(..)) import Foreign.Ptr (castPtr) import Foreign.Storable (Storable(..)) #if __GLASGOW_HASKELL__ >= 702 import GHC.Generics (Generic) #if __GLASGOW_HASKELL__ >= 706 import GHC.Generics (Generic1) #endif #endif -- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. -- This can be used in place of the more traditional but less safe idiom of -- passing in an undefined value with the type, because unlike an @(s -> b)@, -- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the extra -- argument, because the newtype is \"free\" -- -- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore -- there is an extra @k@ showing in the instance haddocks that may cause confusion. newtype Tagged s b = Tagged { unTagged :: b } deriving ( Eq, Ord, Ix, Bounded #if __GLASGOW_HASKELL__ >= 702 , Generic #if __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #endif #if __GLASGOW_HASKELL__ >= 707 , Typeable #endif ) #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 707 instance Typeable2 Tagged where typeOf2 _ = mkTyConApp taggedTyCon [] taggedTyCon :: TyCon #if __GLASGOW_HASKELL__ < 704 taggedTyCon = mkTyCon "Data.Tagged.Tagged" #else taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged" #endif #endif instance (Data s, Data b) => Data (Tagged s b) where gfoldl f z (Tagged b) = z Tagged `f` b toConstr _ = taggedConstr gunfold k z c = case constrIndex c of 1 -> k (z Tagged) _ -> error "gunfold" dataTypeOf _ = taggedDataType dataCast1 f = gcast1 f dataCast2 f = gcast2 f taggedConstr :: Constr taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix {-# INLINE taggedConstr #-} taggedDataType :: DataType taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] {-# INLINE taggedDataType #-} #endif instance Show b => Show (Tagged s b) where showsPrec n (Tagged b) = showParen (n > 10) $ showString "Tagged " . showsPrec 11 b instance Read b => Read (Tagged s b) where readsPrec d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] -#if __GLASGOW_HASKELL__ >= 800 +#if MIN_VERSION_base(4,9,0) instance Semigroup a => Semigroup (Tagged s a) where Tagged a <> Tagged b = Tagged (a <> b) stimes n (Tagged a) = Tagged (stimes n a) instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where mempty = Tagged mempty mappend = (<>) #else instance Monoid a => Monoid (Tagged s a) where mempty = Tagged mempty mappend (Tagged a) (Tagged b) = Tagged (mappend a b) #endif instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} -#if __GLASGOW_HASKELL__ >= 709 +#if MIN_VERSION_base(4,8,0) -- this instance is provided by the bifunctors package for GHC<7.9 instance Bifunctor Tagged where bimap _ g (Tagged b) = Tagged (g b) {-# INLINE bimap #-} #endif -#if __GLASGOW_HASKELL__ >= 801 +#if MIN_VERSION_base(4,10,0) -- these instances are provided by the bifunctors package for GHC<8.1 instance Bifoldable Tagged where bifoldMap _ g (Tagged b) = g b {-# INLINE bifoldMap #-} instance Bitraversable Tagged where bitraverse _ g (Tagged b) = Tagged <$> g b {-# INLINE bitraverse #-} #endif #ifdef MIN_VERSION_deepseq instance NFData b => NFData (Tagged s b) where rnf (Tagged b) = rnf b #endif #ifdef MIN_VERSION_transformers # if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) instance Eq1 (Tagged s) where eq1 = (==) instance Ord1 (Tagged s) where compare1 = compare instance Read1 (Tagged s) where readsPrec1 = readsPrec instance Show1 (Tagged s) where showsPrec1 = showsPrec # else instance Eq1 (Tagged s) where liftEq eq (Tagged a) (Tagged b) = eq a b instance Ord1 (Tagged s) where liftCompare cmp (Tagged a) (Tagged b) = cmp a b instance Read1 (Tagged s) where liftReadsPrec rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show1 (Tagged s) where liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b instance Eq2 Tagged where liftEq2 _ eq (Tagged a) (Tagged b) = eq a b instance Ord2 Tagged where liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b instance Read2 Tagged where liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] instance Show2 Tagged where liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ showString "Tagged " . sp 11 b # endif #endif instance Applicative (Tagged s) where pure = Tagged {-# INLINE pure #-} Tagged f <*> Tagged x = Tagged (f x) {-# INLINE (<*>) #-} _ *> n = n {-# INLINE (*>) #-} instance Monad (Tagged s) where return = pure {-# INLINE return #-} Tagged m >>= k = k m {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance Foldable (Tagged s) where foldMap f (Tagged x) = f x {-# INLINE foldMap #-} fold (Tagged x) = x {-# INLINE fold #-} foldr f z (Tagged x) = f x z {-# INLINE foldr #-} foldl f z (Tagged x) = f z x {-# INLINE foldl #-} foldl1 _ (Tagged x) = x {-# INLINE foldl1 #-} foldr1 _ (Tagged x) = x {-# INLINE foldr1 #-} instance Traversable (Tagged s) where traverse f (Tagged x) = Tagged <$> f x {-# INLINE traverse #-} sequenceA (Tagged x) = Tagged <$> x {-# INLINE sequenceA #-} mapM f (Tagged x) = liftM Tagged (f x) {-# INLINE mapM #-} sequence (Tagged x) = liftM Tagged x {-# INLINE sequence #-} instance Enum a => Enum (Tagged s a) where succ = fmap succ pred = fmap pred toEnum = Tagged . toEnum fromEnum (Tagged x) = fromEnum x enumFrom (Tagged x) = map Tagged (enumFrom x) enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = map Tagged (enumFromThenTo x y z) instance Num a => Num (Tagged s a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = Tagged . fromInteger instance Real a => Real (Tagged s a) where toRational (Tagged x) = toRational x instance Integral a => Integral (Tagged s a) where quot = liftA2 quot rem = liftA2 rem div = liftA2 div mod = liftA2 mod quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = quotRem x y divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where (a, b) = divMod x y toInteger (Tagged x) = toInteger x instance Fractional a => Fractional (Tagged s a) where (/) = liftA2 (/) recip = fmap recip fromRational = Tagged . fromRational instance Floating a => Floating (Tagged s a) where pi = Tagged pi exp = fmap exp log = fmap log sqrt = fmap sqrt sin = fmap sin cos = fmap cos tan = fmap tan asin = fmap asin acos = fmap acos atan = fmap atan sinh = fmap sinh cosh = fmap cosh tanh = fmap tanh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh (**) = liftA2 (**) logBase = liftA2 (**) instance RealFrac a => RealFrac (Tagged s a) where properFraction (Tagged x) = (a, Tagged b) where (a, b) = properFraction x truncate (Tagged x) = truncate x round (Tagged x) = round x ceiling (Tagged x) = ceiling x floor (Tagged x) = floor x instance RealFloat a => RealFloat (Tagged s a) where floatRadix (Tagged x) = floatRadix x floatDigits (Tagged x) = floatDigits x floatRange (Tagged x) = floatRange x decodeFloat (Tagged x) = decodeFloat x encodeFloat m n = Tagged (encodeFloat m n) exponent (Tagged x) = exponent x significand = fmap significand scaleFloat n = fmap (scaleFloat n) isNaN (Tagged x) = isNaN x isInfinite (Tagged x) = isInfinite x isDenormalized (Tagged x) = isDenormalized x isNegativeZero (Tagged x) = isNegativeZero x isIEEE (Tagged x) = isIEEE x atan2 = liftA2 atan2 instance Bits a => Bits (Tagged s a) where Tagged a .&. Tagged b = Tagged (a .&. b) Tagged a .|. Tagged b = Tagged (a .|. b) xor (Tagged a) (Tagged b) = Tagged (xor a b) complement (Tagged a) = Tagged (complement a) shift (Tagged a) i = Tagged (shift a i) shiftL (Tagged a) i = Tagged (shiftL a i) shiftR (Tagged a) i = Tagged (shiftR a i) rotate (Tagged a) i = Tagged (rotate a i) rotateL (Tagged a) i = Tagged (rotateL a i) rotateR (Tagged a) i = Tagged (rotateR a i) bit i = Tagged (bit i) setBit (Tagged a) i = Tagged (setBit a i) clearBit (Tagged a) i = Tagged (clearBit a i) complementBit (Tagged a) i = Tagged (complementBit a i) testBit (Tagged a) i = testBit a i isSigned (Tagged a) = isSigned a bitSize (Tagged a) = bitSize a -- deprecated, but still required :( -#if __GLASGOW_HASKELL__ >= 704 +#if MIN_VERSION_base(4,5,0) unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) popCount (Tagged a) = popCount a #endif -#if __GLASGOW_HASKELL__ >= 708 +#if MIN_VERSION_base(4,7,0) bitSizeMaybe (Tagged a) = bitSizeMaybe a zeroBits = Tagged zeroBits #endif -#if __GLASGOW_HASKELL__ >= 708 +#if MIN_VERSION_base(4,7,0) instance FiniteBits a => FiniteBits (Tagged s a) where finiteBitSize (Tagged a) = finiteBitSize a -# if __GLASGOW_HASKELL__ >= 710 +# if MIN_VERSION_base(4,8,0) countLeadingZeros (Tagged a) = countLeadingZeros a countTrailingZeros (Tagged a) = countTrailingZeros a # endif #endif instance IsString a => IsString (Tagged s a) where fromString = Tagged . fromString instance Storable a => Storable (Tagged s a) where sizeOf t = sizeOf a where Tagged a = Tagged undefined `asTypeOf` t alignment t = alignment a where Tagged a = Tagged undefined `asTypeOf` t peek ptr = Tagged <$> peek (castPtr ptr) poke ptr (Tagged a) = poke (castPtr ptr) a peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a -- | Some times you need to change the tag you have lying around. -- Idiomatic usage is to make a new combinator for the relationship between the -- tags that you want to enforce, and define that combinator using 'retag'. -- -- @ -- data Succ n -- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a -- retagSucc = 'retag' -- @ retag :: Tagged s b -> Tagged t b retag = Tagged . unTagged {-# INLINE retag #-} -- | Alias for 'unTagged' untag :: Tagged s b -> b untag = unTagged -- | Tag a value with its own type. tagSelf :: a -> Tagged a a tagSelf = Tagged {-# INLINE tagSelf #-} -- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. asTaggedTypeOf :: s -> tagged s b -> s asTaggedTypeOf = const {-# INLINE asTaggedTypeOf #-} witness :: Tagged a b -> a -> b witness (Tagged b) _ = b {-# INLINE witness #-} -- | 'untagSelf' is a type-restricted version of 'untag'. untagSelf :: Tagged a a -> a untagSelf (Tagged x) = x {-# INLINE untagSelf #-} -- | Convert from a 'Tagged' representation to a representation -- based on a 'Proxy'. proxy :: Tagged s a -> proxy s -> a proxy (Tagged x) _ = x {-# INLINE proxy #-} -- | Convert from a representation based on a 'Proxy' to a 'Tagged' -- representation. unproxy :: (Proxy s -> a) -> Tagged s a unproxy f = Tagged (f Proxy) {-# INLINE unproxy #-} -- | Another way to convert a proxy to a tag. tagWith :: proxy s -> a -> Tagged s a tagWith _ = Tagged {-# INLINE tagWith #-} -- | Some times you need to change the proxy you have lying around. -- Idiomatic usage is to make a new combinator for the relationship -- between the proxies that you want to enforce, and define that -- combinator using 'reproxy'. -- -- @ -- data Succ n -- reproxySucc :: proxy n -> 'Proxy' (Succ n) -- reproxySucc = 'reproxy' -- @ reproxy :: proxy a -> Proxy b reproxy _ = Proxy
ekmett/tagged
c5dfa76e7d8f38f9c40102ebd41804cdb9ec2310
Allow template-haskell-2.12.0.0
diff --git a/tagged.cabal b/tagged.cabal index 6bb6676..8eb3849 100644 --- a/tagged.cabal +++ b/tagged.cabal @@ -1,67 +1,67 @@ name: tagged version: 0.8.5 license: BSD3 license-file: LICENSE author: Edward A. Kmett maintainer: Edward A. Kmett <[email protected]> stability: experimental category: Data, Phantom Types synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments homepage: http://github.com/ekmett/tagged bug-reports: http://github.com/ekmett/tagged/issues copyright: 2009-2015 Edward A. Kmett description: Haskell 98 phantom types to avoid unsafely passing dummy arguments build-type: Simple cabal-version: >= 1.10 extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs source-repository head type: git location: git://github.com/ekmett/tagged.git flag deepseq description: You can disable the use of the `deepseq` package using `-f-deepseq`. . Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True flag transformers description: You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. . Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. default: True manual: True library default-language: Haskell98 other-extensions: CPP build-depends: base >= 2 && < 5 ghc-options: -Wall hs-source-dirs: src exposed-modules: Data.Tagged if !impl(hugs) cpp-options: -DLANGUAGE_DeriveDataTypeable other-extensions: DeriveDataTypeable if impl(ghc<7.7) hs-source-dirs: old exposed-modules: Data.Proxy other-modules: Paths_tagged if impl(ghc>=7.2 && <7.5) build-depends: ghc-prim if impl(ghc>=7.6) exposed-modules: Data.Proxy.TH - build-depends: template-haskell >= 2.8 && < 2.12 + build-depends: template-haskell >= 2.8 && < 2.13 if flag(deepseq) build-depends: deepseq >= 1.1 && < 1.5 if flag(transformers) build-depends: transformers >= 0.2 && < 0.6, transformers-compat >= 0.5 && < 1
ekmett/tagged
93cd87830733ed641409a2a14776973e8be600cc
Delete unneeded GHC 7.10.1 hack in .travis.yml
diff --git a/.travis.yml b/.travis.yml index b671b8f..67cef36 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,146 +1,141 @@ # This file has been generated -- see https://github.com/hvr/multi-ghc-travis language: c sudo: false cache: directories: - $HOME/.cabsnap - $HOME/.cabal/packages - $HOME/.stack before_cache: - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.tar matrix: include: - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal compiler: ": #GHC 7.0.4" addons: {apt: {packages: [cabal-install-1.16,ghc-7.0.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal compiler: ": #GHC 7.2.2" addons: {apt: {packages: [cabal-install-1.16,ghc-7.2.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.4.2 BUILD=cabal compiler: ": #GHC 7.4.2" addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.16 GHCVER=7.6.3 BUILD=cabal compiler: ": #GHC 7.6.3" addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.18 GHCVER=7.8.4 BUILD=cabal compiler: ": #GHC 7.8.4" addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack STACK_YAML=stack-7.8.yaml STACK_OPTIONS=--skip-ghc-check # compiler: ": #GHC 7.8.4" # addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack STACK_YAML=stack-7.8.yaml # os: osx - - env: CABALVER=1.22 GHCVER=7.10.1 BUILD=cabal - compiler: ": #GHC 7.10.1" - addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - # - env: BUILD=stack STACK_OPTIONS=--skip-ghc-check # compiler: ": #GHC 7.10.1" # addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.22 GHCVER=7.10.3 BUILD=cabal compiler: ": #GHC 7.10.3" addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=1.24 GHCVER=8.0.1 BUILD=cabal compiler: ": #GHC 8.0.1" addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} - env: CABALVER=head GHCVER=head BUILD=cabal compiler: ": #GHC head" addons: {apt: {packages: [cabal-install-head,ghc-head,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} # - env: BUILD=stack # os: osx allow_failures: - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal - env: CABALVER=head GHCVER=head BUILD=cabal before_install: - unset CC - case "$BUILD" in stack) export STACK_VERSION=0.1.3.0; mkdir -p ~/bin; travis_retry curl -L https://github.com/commercialhaskell/stack/releases/download/v$STACK_VERSION/stack-$STACK_VERSION-x86_64-$TRAVIS_OS_NAME.gz | gunzip > ~/bin/stack; chmod a+x ~/bin/stack; scripts/travis_long stack --no-terminal setup; export PATH=~/bin:$PATH;; cabal) export HAPPYVER=1.19.5 export ALEXVER=3.1.4 export PATH=~/.cabal/bin:/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:/opt/happy/$HAPPYVER/bin:/opt/alex/$ALEXVER/bin:$PATH;; esac install: - case "$BUILD" in stack) scripts/travis_long stack --no-terminal $STACK_OPTIONS build --only-snapshot -j2;; cabal) echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]" cabal --version; if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ]; then zcat $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz > $HOME/.cabal/packages/hackage.haskell.org/00-index.tar; fi; travis_retry cabal update; cabal install --only-dependencies --enable-tests --enable-benchmarks --dry -v > installplan.txt; sed -i -e '1,/^Resolving /d' installplan.txt; cat installplan.txt; if diff -u installplan.txt $HOME/.cabsnap/installplan.txt; then echo "cabal build-cache HIT"; rm -rfv .ghc; cp -a $HOME/.cabsnap/ghc $HOME/.ghc; cp -a $HOME/.cabsnap/lib $HOME/.cabsnap/share $HOME/.cabsnap/bin $HOME/.cabal/; else echo "cabal build-cache MISS"; rm -rf $HOME/.cabsnap; mkdir -p $HOME/.ghc $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin; cabal install --only-dependencies --enable-tests --enable-benchmarks; - if [ "$GHCVER" = "7.10.1" ]; then cabal install Cabal-1.22.4.0; fi; fi; if [ ! -d $HOME/.cabsnap ]; then echo "snapshotting package-db to build-cache"; mkdir $HOME/.cabsnap; cp -a $HOME/.ghc $HOME/.cabsnap/ghc; cp -a $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin installplan.txt $HOME/.cabsnap/; fi;; esac # snapshot package-db on cache miss # Here starts the actual work to be performed for the package under test; # any command which exits with a non-zero exit code causes the build to fail. script: - case "$BUILD" in stack) scripts/travis_long stack --no-terminal $STACK_OPTIONS build -j2;; cabal) cabal configure --enable-tests -v2; cabal build; cabal test; cabal bench || true; cabal sdist || true; SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz && (cd dist && cabal install --force-reinstalls "$SRC_TGZ");; esac notifications: irc: channels: - "irc.freenode.org#haskell-lens" skip_join: true template: - "\x0313tagged\x0f/\x0306%{branch}\x0f \x0314%{commit}\x0f %{message} \x0302\x1f%{build_url}\x0f" # EOF
ekmett/tagged
3d36d00d6f33ac383b29a9a10a2373e5e9848420
Version 0.8.5
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..680208e --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +dist/ +.hsenv/ +docs +wiki +TAGS +tags +wip +.DS_Store +.*.swp +.*.swo +*.o +*.hi +*~ +*# diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..b671b8f --- /dev/null +++ b/.travis.yml @@ -0,0 +1,146 @@ +# This file has been generated -- see https://github.com/hvr/multi-ghc-travis +language: c +sudo: false + +cache: + directories: + - $HOME/.cabsnap + - $HOME/.cabal/packages + - $HOME/.stack + +before_cache: + - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log + - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.tar + +matrix: + include: + - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal + compiler: ": #GHC 7.0.4" + addons: {apt: {packages: [cabal-install-1.16,ghc-7.0.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + + - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal + compiler: ": #GHC 7.2.2" + addons: {apt: {packages: [cabal-install-1.16,ghc-7.2.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + + - env: CABALVER=1.16 GHCVER=7.4.2 BUILD=cabal + compiler: ": #GHC 7.4.2" + addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + + - env: CABALVER=1.16 GHCVER=7.6.3 BUILD=cabal + compiler: ": #GHC 7.6.3" + addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + + - env: CABALVER=1.18 GHCVER=7.8.4 BUILD=cabal + compiler: ": #GHC 7.8.4" + addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + +# - env: BUILD=stack STACK_YAML=stack-7.8.yaml STACK_OPTIONS=--skip-ghc-check +# compiler: ": #GHC 7.8.4" +# addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + +# - env: BUILD=stack STACK_YAML=stack-7.8.yaml +# os: osx + + - env: CABALVER=1.22 GHCVER=7.10.1 BUILD=cabal + compiler: ": #GHC 7.10.1" + addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + +# - env: BUILD=stack STACK_OPTIONS=--skip-ghc-check +# compiler: ": #GHC 7.10.1" +# addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + + - env: CABALVER=1.22 GHCVER=7.10.3 BUILD=cabal + compiler: ": #GHC 7.10.3" + addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + + - env: CABALVER=1.24 GHCVER=8.0.1 BUILD=cabal + compiler: ": #GHC 8.0.1" + addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.1,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + + - env: CABALVER=head GHCVER=head BUILD=cabal + compiler: ": #GHC head" + addons: {apt: {packages: [cabal-install-head,ghc-head,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} + +# - env: BUILD=stack +# os: osx + + allow_failures: + - env: CABALVER=1.16 GHCVER=7.0.4 BUILD=cabal + - env: CABALVER=1.16 GHCVER=7.2.2 BUILD=cabal + - env: CABALVER=head GHCVER=head BUILD=cabal + +before_install: + - unset CC + - case "$BUILD" in + stack) + export STACK_VERSION=0.1.3.0; + mkdir -p ~/bin; + travis_retry curl -L https://github.com/commercialhaskell/stack/releases/download/v$STACK_VERSION/stack-$STACK_VERSION-x86_64-$TRAVIS_OS_NAME.gz | gunzip > ~/bin/stack; + chmod a+x ~/bin/stack; + scripts/travis_long stack --no-terminal setup; + export PATH=~/bin:$PATH;; + cabal) + export HAPPYVER=1.19.5 + export ALEXVER=3.1.4 + export PATH=~/.cabal/bin:/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:/opt/happy/$HAPPYVER/bin:/opt/alex/$ALEXVER/bin:$PATH;; + esac +install: + - case "$BUILD" in + stack) + scripts/travis_long stack --no-terminal $STACK_OPTIONS build --only-snapshot -j2;; + cabal) + echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]" + cabal --version; + if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ]; + then + zcat $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz > + $HOME/.cabal/packages/hackage.haskell.org/00-index.tar; + fi; + travis_retry cabal update; + cabal install --only-dependencies --enable-tests --enable-benchmarks --dry -v > installplan.txt; + sed -i -e '1,/^Resolving /d' installplan.txt; cat installplan.txt; + if diff -u installplan.txt $HOME/.cabsnap/installplan.txt; then + echo "cabal build-cache HIT"; + rm -rfv .ghc; + cp -a $HOME/.cabsnap/ghc $HOME/.ghc; + cp -a $HOME/.cabsnap/lib $HOME/.cabsnap/share $HOME/.cabsnap/bin $HOME/.cabal/; + else + echo "cabal build-cache MISS"; + rm -rf $HOME/.cabsnap; + mkdir -p $HOME/.ghc $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin; + cabal install --only-dependencies --enable-tests --enable-benchmarks; + if [ "$GHCVER" = "7.10.1" ]; then cabal install Cabal-1.22.4.0; fi; + fi; + if [ ! -d $HOME/.cabsnap ]; then + echo "snapshotting package-db to build-cache"; + mkdir $HOME/.cabsnap; + cp -a $HOME/.ghc $HOME/.cabsnap/ghc; + cp -a $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin installplan.txt $HOME/.cabsnap/; + fi;; + esac + +# snapshot package-db on cache miss + +# Here starts the actual work to be performed for the package under test; +# any command which exits with a non-zero exit code causes the build to fail. +script: + - case "$BUILD" in + stack) + scripts/travis_long stack --no-terminal $STACK_OPTIONS build -j2;; + cabal) + cabal configure --enable-tests -v2; + cabal build; + cabal test; + cabal bench || true; + cabal sdist || true; + SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz && (cd dist && cabal install --force-reinstalls "$SRC_TGZ");; + esac + +notifications: + irc: + channels: + - "irc.freenode.org#haskell-lens" + skip_join: true + template: + - "\x0313tagged\x0f/\x0306%{branch}\x0f \x0314%{commit}\x0f %{message} \x0302\x1f%{build_url}\x0f" +# EOF diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown new file mode 100644 index 0000000..665207d --- /dev/null +++ b/CHANGELOG.markdown @@ -0,0 +1,80 @@ +0.8.5 +----- +* Support `Data.Bifoldable`/`Data.Bitraversable` in `base` for GHC 8.1+. +* Backport the `Eq1`, `Ord1`, `Read1`, and `Show1` instances for `Proxy` from `base-4.9` +* Add `Eq1`/`2`, `Ord1`/`2`, `Read1`/`2`, and `Show1`/`2` instances for `Tagged` + +0.8.4 +----- +* Backport the `Alternative`, `MonadPlus`, and `MonadZip` instances for `Proxy` from `base-4.9` +* Add `Bits`, `FiniteBits`, `IsString`, and `Storable` instances for `Tagged` + +0.8.3 +----- +* Manual `Generic1` support to work around a bug in GHC 7.6 +* Invert the dependency to supply the `Semigroup` instance ourselves when building on GHC 8 + +0.8.2 +------- +* `deepseq` support. +* Widened `template-haskell` dependency bounds. + +0.8.1 +----- +* Add `KProxy` to the backwards compatibility `Data.Proxy` module. +* Add a `Generic` instance to `Proxy`. + +0.8.0.1 +------- +* Fix builds on GHC 7.4. + +0.8 +--- +* Added `Data.Proxy.TH`, based on the code from `Frames` by Anthony Cowley. +* Removed `reproxy` from `Data.Proxy`. This is a bad API decision, but it isn't present in GHC's `Data.Proxy`, and this makes the API more stable. + +0.7.3 +--- +* Support `Data.Bifunctor` in `base` for GHC 7.9+. + +0.7.2 +----- +* Fixed warning on GHC 7.8 + +0.7.1 +----- +* Added `tagWith`. + +0.7 +--- +* `Data.Proxy` has moved into base as of GHC 7.7 for use in the new `Data.Typeable`. We no longer export + it for GHC >= 7.7. The most notable change in the module from the migration into base is the loss of + the `reproxy` function. + +0.6.2 +----- +* Allowed polymorphic arguments where possible. + +0.6.1 +----- +* Needlessly claim that this entirely pure package is `Trustworthy`! + +0.6 +--- +* On GHC 7.7, we now still export the instances we used to for `Data.Proxy.Proxy` as orphans if need be. + +0.5 +--- +* On GHC 7.7 we now simply export `Data.Typeable.Proxy` rather than make our own type. We still re-export it. + +0.4.5 +----- +* Added `witness` + +0.4.4 +----- +* Actually working polymorphic kind support + +0.4.3 +----- +* Added polymorphic kind support diff --git a/HLint.hs b/HLint.hs new file mode 100644 index 0000000..52eb49d --- /dev/null +++ b/HLint.hs @@ -0,0 +1,2 @@ +ignore "Use camelCase" +ignore "Eta reduce" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..db04615 --- /dev/null +++ b/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2009-2015 Edward Kmett +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of Edward Kmett nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.markdown b/README.markdown new file mode 100644 index 0000000..f7e55d8 --- /dev/null +++ b/README.markdown @@ -0,0 +1,6 @@ +tagged +====== + +[![Hackage](https://img.shields.io/hackage/v/tagged.svg)](https://hackage.haskell.org/package/tagged) [![Build Status](https://secure.travis-ci.org/ekmett/tagged.png?branch=master)](http://travis-ci.org/ekmett/tagged) + +Values carrying an extra [phantom type](https://wiki.haskell.org/Phantom_type) tag. diff --git a/Setup.lhs b/Setup.lhs new file mode 100644 index 0000000..6cbd928 --- /dev/null +++ b/Setup.lhs @@ -0,0 +1,7 @@ +#!/usr/bin/runhaskell +> module Main (main) where + +> import Distribution.Simple + +> main :: IO () +> main = defaultMain diff --git a/old/Data/Proxy.hs b/old/Data/Proxy.hs new file mode 100644 index 0000000..3cce748 --- /dev/null +++ b/old/Data/Proxy.hs @@ -0,0 +1,279 @@ +{-# LANGUAGE CPP #-} +#ifdef LANGUAGE_DeriveDataTypeable +{-# LANGUAGE DeriveDataTypeable #-} +#endif +#if __GLASGOW_HASKELL__ >= 706 +{-# LANGUAGE KindSignatures #-} +{-# LANGUAGE PolyKinds #-} +#endif +#if __GLASGOW_HASKELL__ >= 707 +{-# LANGUAGE StandaloneDeriving #-} +#endif +#if __GLASGOW_HASKELL__ >= 702 +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE EmptyDataDecls #-} +{-# LANGUAGE Trustworthy #-} +{-# LANGUAGE TypeFamilies #-} +#endif +{-# OPTIONS_GHC -fno-warn-orphans #-} +---------------------------------------------------------------------------- +-- | +-- Module : Data.Proxy +-- Copyright : 2009-2013 Edward Kmett +-- License : BSD3 +-- +-- Maintainer : Edward Kmett <[email protected]> +-- Stability : experimental +-- Portability : portable +-- +------------------------------------------------------------------------------- +module Data.Proxy + ( + -- * Proxy values + Proxy(..) + , asProxyTypeOf + , KProxy(..) + ) where + +import Control.Applicative (Applicative(..), Alternative(..)) +import Control.Monad (MonadPlus(..)) +#if MIN_VERSION_base(4,4,0) +import Control.Monad.Zip (MonadZip(..)) +#endif +#ifdef MIN_VERSION_deepseq +import Control.DeepSeq (NFData(..)) +#endif +#ifdef MIN_VERSION_transformers +import Data.Functor.Classes (Eq1(..), Ord1(..), Read1(..), Show1(..)) +#endif +import Data.Traversable (Traversable(..)) +import Data.Foldable (Foldable(..)) +import Data.Ix (Ix(..)) +import Data.Monoid +#ifdef __GLASGOW_HASKELL__ +import GHC.Arr (unsafeIndex, unsafeRangeSize) +import Data.Data +#if __GLASGOW_HASKELL__ >= 702 +import GHC.Generics hiding (Fixity(..)) +#endif +#endif + +#if __GLASGOW_HASKELL__ >= 707 +deriving instance Typeable Proxy +#else +data Proxy s = Proxy +#if __GLASGOW_HASKELL__ >= 702 + deriving Generic + +-- We have to implement the Generic1 instance manually due to an old +-- bug in GHC 7.6. This is mostly copied from the output of +-- +-- deriving instance Generic1 Proxy +-- +-- Compiled with -ddump-deriv on a more recent GHC. +instance Generic1 Proxy where + type Rep1 Proxy = D1 ProxyMetaData (C1 ProxyMetaCons U1) + from1 Proxy = M1 (M1 U1) + to1 (M1 (M1 U1)) = Proxy + +data ProxyMetaData +data ProxyMetaCons + +instance Datatype ProxyMetaData where + datatypeName _ = "Proxy" + moduleName _ = "Data.Proxy" + +instance Constructor ProxyMetaCons where + conName _ = "Proxy" +#endif +#endif + +instance Eq (Proxy s) where + _ == _ = True + +instance Ord (Proxy s) where + compare _ _ = EQ + +instance Show (Proxy s) where + showsPrec _ _ = showString "Proxy" + +instance Read (Proxy s) where + readsPrec d = readParen (d > 10) (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) + +#ifdef __GLASGOW_HASKELL__ +#if __GLASGOW_HASKELL__ < 707 +instance Typeable1 Proxy where + typeOf1 _ = mkTyConApp proxyTyCon [] + +proxyTyCon :: TyCon +#if __GLASGOW_HASKELL__ < 704 +proxyTyCon = mkTyCon "Data.Proxy.Proxy" +#else +proxyTyCon = mkTyCon3 "tagged" "Data.Proxy" "Proxy" +#endif +{-# NOINLINE proxyTyCon #-} +#endif + +instance Data s => Data (Proxy s) where + gfoldl _ z _ = z Proxy + toConstr _ = proxyConstr + gunfold _ z c = case constrIndex c of + 1 -> z Proxy + _ -> error "gunfold" + dataTypeOf _ = proxyDataType + dataCast1 f = gcast1 f + +proxyConstr :: Constr +proxyConstr = mkConstr proxyDataType "Proxy" [] Prefix +{-# NOINLINE proxyConstr #-} + +proxyDataType :: DataType +proxyDataType = mkDataType "Data.Proxy.Proxy" [proxyConstr] +{-# NOINLINE proxyDataType #-} +#endif + +instance Enum (Proxy s) where + succ _ = error "Proxy.succ" + pred _ = error "Proxy.pred" + fromEnum _ = 0 + toEnum 0 = Proxy + toEnum _ = error "Proxy.toEnum: 0 expected" + enumFrom _ = [Proxy] + enumFromThen _ _ = [Proxy] + enumFromThenTo _ _ _ = [Proxy] + enumFromTo _ _ = [Proxy] + +instance Ix (Proxy s) where + range _ = [Proxy] + index _ _ = 0 + inRange _ _ = True + rangeSize _ = 1 +#ifdef __GLASGOW_HASKELL__ + unsafeIndex _ _ = 0 + unsafeRangeSize _ = 1 +#endif + +instance Bounded (Proxy s) where + minBound = Proxy + maxBound = Proxy + +#ifdef MIN_VERSION_deepseq +instance NFData (Proxy s) where + rnf Proxy = () +#endif + +#ifdef MIN_VERSION_transformers +# if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) +instance Eq1 Proxy where + eq1 = (==) + +instance Ord1 Proxy where + compare1 = compare + +instance Read1 Proxy where + readsPrec1 = readsPrec + +instance Show1 Proxy where + showsPrec1 = showsPrec +# else +instance Eq1 Proxy where + liftEq _ _ _ = True + +instance Ord1 Proxy where + liftCompare _ _ _ = EQ + +instance Show1 Proxy where + liftShowsPrec _ _ _ _ = showString "Proxy" + +instance Read1 Proxy where + liftReadsPrec _ _ d = + readParen (d > 10) (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) +# endif +#endif + +instance Functor Proxy where + fmap _ _ = Proxy + {-# INLINE fmap #-} + +instance Applicative Proxy where + pure _ = Proxy + {-# INLINE pure #-} + _ <*> _ = Proxy + {-# INLINE (<*>) #-} + +instance Alternative Proxy where + empty = Proxy + {-# INLINE empty #-} + _ <|> _ = Proxy + {-# INLINE (<|>) #-} + +instance Monoid (Proxy s) where + mempty = Proxy + {-# INLINE mempty #-} + mappend _ _ = Proxy + {-# INLINE mappend #-} + mconcat _ = Proxy + {-# INLINE mconcat #-} + +instance Monad Proxy where + return _ = Proxy + {-# INLINE return #-} + _ >>= _ = Proxy + {-# INLINE (>>=) #-} + +instance MonadPlus Proxy where + mzero = Proxy + {-# INLINE mzero #-} + mplus _ _ = Proxy + {-# INLINE mplus #-} + +#if MIN_VERSION_base(4,4,0) +instance MonadZip Proxy where + mzipWith _ _ _ = Proxy + {-# INLINE mzipWith #-} +#endif + +instance Foldable Proxy where + foldMap _ _ = mempty + {-# INLINE foldMap #-} + fold _ = mempty + {-# INLINE fold #-} + foldr _ z _ = z + {-# INLINE foldr #-} + foldl _ z _ = z + {-# INLINE foldl #-} + foldl1 _ _ = error "foldl1: Proxy" + {-# INLINE foldl1 #-} + foldr1 _ _ = error "foldr1: Proxy" + {-# INLINE foldr1 #-} + +instance Traversable Proxy where + traverse _ _ = pure Proxy + {-# INLINE traverse #-} + sequenceA _ = pure Proxy + {-# INLINE sequenceA #-} + mapM _ _ = return Proxy + {-# INLINE mapM #-} + sequence _ = return Proxy + {-# INLINE sequence #-} + +-- | 'asProxyTypeOf' is a type-restricted version of 'const'. +-- It is usually used as an infix operator, and its typing forces its first +-- argument (which is usually overloaded) to have the same type as the tag +-- of the second. +asProxyTypeOf :: a -> proxy a -> a +asProxyTypeOf = const +{-# INLINE asProxyTypeOf #-} + +-- | A concrete, promotable proxy type, for use at the kind level +-- There are no instances for this because it is intended at the kind level only +data KProxy +#if __GLASGOW_HASKELL__ >= 706 + (t :: *) +#else + t +#endif + = KProxy +#if defined(LANGUAGE_DeriveDataTypeable) + deriving Typeable +#endif diff --git a/scripts/travis_long b/scripts/travis_long new file mode 100755 index 0000000..54b6d15 --- /dev/null +++ b/scripts/travis_long @@ -0,0 +1,17 @@ +#!/bin/bash + +$* & +pidA=$! +minutes=0 + +while true; do sleep 60; ((minutes++)); echo -e "\033[0;32m$minutes minute(s) elapsed.\033[0m"; done & + pidB=$! + + wait $pidA + exitCode=$? + + echo -e "\033[0;32m$* finished.\033[0m" + + kill -9 $pidB + + exit $exitCode diff --git a/src/Data/Proxy/TH.hs b/src/Data/Proxy/TH.hs new file mode 100644 index 0000000..f571ea3 --- /dev/null +++ b/src/Data/Proxy/TH.hs @@ -0,0 +1,96 @@ +{-# LANGUAGE CPP #-} +#ifndef MIN_VERSION_template_haskell +#define MIN_VERSION_template_haskell(x,y,z) 1 +#endif +module Data.Proxy.TH + ( pr +#if MIN_VERSION_template_haskell(2,8,0) + , pr1 +#endif + ) where + +import Data.Char +#if __GLASGOW_HASKELL__ < 710 +import Data.Functor +#endif +#if __GLASGOW_HASKELL__ < 707 +import Data.Version (showVersion) +import Paths_tagged +#endif +import Language.Haskell.TH +import Language.Haskell.TH.Quote +import Language.Haskell.TH.Syntax + +proxy_d, proxy_tc :: Name +#if __GLASGOW_HASKELL__ >= 707 +proxy_d = mkNameG_d "base" "Data.Proxy" "Proxy" +proxy_tc = mkNameG_tc "base" "Data.Proxy" "Proxy" +#else +proxy_d = mkNameG_d taggedPackageKey "Data.Proxy" "Proxy" +proxy_tc = mkNameG_tc taggedPackageKey "Data.Proxy" "Proxy" + +-- note: On 7.10+ this would use CURRENT_PACKAGE_KEY if we still housed the key. +taggedPackageKey :: String +taggedPackageKey = "tagged-" ++ showVersion version +#endif + +proxyTypeQ :: TypeQ -> TypeQ +proxyTypeQ t = appT (conT proxy_tc) t + +proxyExpQ :: TypeQ -> ExpQ +proxyExpQ t = sigE (conE proxy_d) (proxyTypeQ t) + +proxyPatQ :: TypeQ -> PatQ +proxyPatQ t = sigP (conP proxy_d []) (proxyTypeQ t) + +-- | A proxy value quasiquoter. @[pr|T|]@ will splice an expression +-- @Proxy::Proxy T@, while @[pr|A,B,C|]@ will splice in a value of +-- @Proxy :: Proxy [A,B,C]@. + +-- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. +pr :: QuasiQuoter +pr = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where + mkProxy :: (TypeQ -> r) -> String -> r + mkProxy p s = case ts of + [h@(t:_)] + | isUpper t -> p $ head <$> cons + | otherwise -> p $ varT $ mkName h +#if MIN_VERSION_template_haskell(2,8,0) + _ -> p $ mkList <$> cons +#endif + where + ts = map strip $ splitOn ',' s + cons = mapM (conT . mkName) ts +#if MIN_VERSION_template_haskell(2,8,0) + mkList = foldr (AppT . AppT PromotedConsT) PromotedNilT +#endif + +#if MIN_VERSION_template_haskell(2,8,0) +-- | Like 'pr', but takes a single type, which is used to produce a +-- 'Proxy' for a single-element list containing only that type. This +-- is useful for passing a single type to a function that wants a list +-- of types. + +-- TODO: parse a richer syntax for the types involved here so we can include spaces, applications, etc. +pr1 :: QuasiQuoter +pr1 = QuasiQuoter (mkProxy proxyExpQ) (mkProxy proxyPatQ) (mkProxy proxyTypeQ) undefined where + sing x = AppT (AppT PromotedConsT x) PromotedNilT + mkProxy p s = case s of + t:_ + | isUpper t -> p (fmap sing (conT $ mkName s)) + | otherwise -> p (fmap sing (varT $ mkName s)) + _ -> error "Empty string passed to pr1" +#endif + +-- | Split on a delimiter. +splitOn :: Eq a => a -> [a] -> [[a]] +splitOn d = go where + go [] = [] + go xs = case t of + [] -> [h] + (_:t') -> h : go t' + where (h,t) = break (== d) xs + +-- | Remove white space from both ends of a 'String'. +strip :: String -> String +strip = takeWhile (not . isSpace) . dropWhile isSpace diff --git a/src/Data/Tagged.hs b/src/Data/Tagged.hs new file mode 100644 index 0000000..3a91f00 --- /dev/null +++ b/src/Data/Tagged.hs @@ -0,0 +1,488 @@ +{-# LANGUAGE CPP #-} +#ifdef LANGUAGE_DeriveDataTypeable +{-# LANGUAGE DeriveDataTypeable #-} +#endif +#if __GLASGOW_HASKELL__ >= 706 +{-# LANGUAGE PolyKinds #-} +#endif +#if __GLASGOW_HASKELL__ >= 702 +{-# LANGUAGE DeriveGeneric #-} +#if __GLASGOW_HASKELL__ < 710 +{-# LANGUAGE Trustworthy #-} +#endif +#endif + +{-# OPTIONS_GHC -fno-warn-deprecations #-} +---------------------------------------------------------------------------- +-- | +-- Module : Data.Tagged +-- Copyright : 2009-2015 Edward Kmett +-- License : BSD3 +-- +-- Maintainer : Edward Kmett <[email protected]> +-- Stability : experimental +-- Portability : portable +-- +------------------------------------------------------------------------------- + +module Data.Tagged + ( + -- * Tagged values + Tagged(..) + , retag + , untag + , tagSelf + , untagSelf + , asTaggedTypeOf + , witness + -- * Conversion + , proxy + , unproxy + , tagWith + -- * Proxy methods GHC dropped + , reproxy + ) where + +#if __GLASGOW_HASKELL__ >= 710 +import Control.Applicative (liftA2) +#else +import Control.Applicative ((<$>), liftA2, Applicative(..)) +import Data.Traversable (Traversable(..)) +import Data.Monoid +#endif +import Data.Bits +import Data.Foldable (Foldable(..)) +#ifdef MIN_VERSION_deepseq +import Control.DeepSeq (NFData(..)) +#endif +#ifdef MIN_VERSION_transformers +import Data.Functor.Classes ( Eq1(..), Ord1(..), Read1(..), Show1(..) +# if !(MIN_VERSION_transformers(0,4,0)) || MIN_VERSION_transformers(0,5,0) + , Eq2(..), Ord2(..), Read2(..), Show2(..) +# endif + ) +#endif +import Control.Monad (liftM) +#if __GLASGOW_HASKELL__ >= 709 +import Data.Bifunctor +#endif +#if __GLASGOW_HASKELL__ >= 801 +import Data.Bifoldable (Bifoldable(..)) +import Data.Bitraversable (Bitraversable(..)) +#endif +#ifdef __GLASGOW_HASKELL__ +import Data.Data +#endif +import Data.Ix (Ix(..)) +#if __GLASGOW_HASKELL__ < 707 +import Data.Proxy +#endif +#if __GLASGOW_HASKELL__ >= 800 +import Data.Semigroup (Semigroup(..)) +#endif +import Data.String (IsString(..)) +import Foreign.Ptr (castPtr) +import Foreign.Storable (Storable(..)) +#if __GLASGOW_HASKELL__ >= 702 +import GHC.Generics (Generic) +#if __GLASGOW_HASKELL__ >= 706 +import GHC.Generics (Generic1) +#endif +#endif + +-- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@. +-- This can be used in place of the more traditional but less safe idiom of +-- passing in an undefined value with the type, because unlike an @(s -> b)@, +-- a @'Tagged' s b@ can't try to use the argument @s@ as a real value. +-- +-- Moreover, you don't have to rely on the compiler to inline away the extra +-- argument, because the newtype is \"free\" +-- +-- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore +-- there is an extra @k@ showing in the instance haddocks that may cause confusion. +newtype Tagged s b = Tagged { unTagged :: b } deriving + ( Eq, Ord, Ix, Bounded +#if __GLASGOW_HASKELL__ >= 702 + , Generic +#if __GLASGOW_HASKELL__ >= 706 + , Generic1 +#endif +#endif + +#if __GLASGOW_HASKELL__ >= 707 + , Typeable +#endif + + ) + +#ifdef __GLASGOW_HASKELL__ +#if __GLASGOW_HASKELL__ < 707 +instance Typeable2 Tagged where + typeOf2 _ = mkTyConApp taggedTyCon [] + +taggedTyCon :: TyCon +#if __GLASGOW_HASKELL__ < 704 +taggedTyCon = mkTyCon "Data.Tagged.Tagged" +#else +taggedTyCon = mkTyCon3 "tagged" "Data.Tagged" "Tagged" +#endif + +#endif + +instance (Data s, Data b) => Data (Tagged s b) where + gfoldl f z (Tagged b) = z Tagged `f` b + toConstr _ = taggedConstr + gunfold k z c = case constrIndex c of + 1 -> k (z Tagged) + _ -> error "gunfold" + dataTypeOf _ = taggedDataType + dataCast1 f = gcast1 f + dataCast2 f = gcast2 f + +taggedConstr :: Constr +taggedConstr = mkConstr taggedDataType "Tagged" [] Prefix +{-# INLINE taggedConstr #-} + +taggedDataType :: DataType +taggedDataType = mkDataType "Data.Tagged.Tagged" [taggedConstr] +{-# INLINE taggedDataType #-} +#endif + +instance Show b => Show (Tagged s b) where + showsPrec n (Tagged b) = showParen (n > 10) $ + showString "Tagged " . + showsPrec 11 b + +instance Read b => Read (Tagged s b) where + readsPrec d = readParen (d > 10) $ \r -> + [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- readsPrec 11 s] + +#if __GLASGOW_HASKELL__ >= 800 +instance Semigroup a => Semigroup (Tagged s a) where + Tagged a <> Tagged b = Tagged (a <> b) + stimes n (Tagged a) = Tagged (stimes n a) + +instance (Semigroup a, Monoid a) => Monoid (Tagged s a) where + mempty = Tagged mempty + mappend = (<>) +#else +instance Monoid a => Monoid (Tagged s a) where + mempty = Tagged mempty + mappend (Tagged a) (Tagged b) = Tagged (mappend a b) +#endif + +instance Functor (Tagged s) where + fmap f (Tagged x) = Tagged (f x) + {-# INLINE fmap #-} + +#if __GLASGOW_HASKELL__ >= 709 +-- this instance is provided by the bifunctors package for GHC<7.9 +instance Bifunctor Tagged where + bimap _ g (Tagged b) = Tagged (g b) + {-# INLINE bimap #-} +#endif + +#if __GLASGOW_HASKELL__ >= 801 +-- these instances are provided by the bifunctors package for GHC<8.1 +instance Bifoldable Tagged where + bifoldMap _ g (Tagged b) = g b + {-# INLINE bifoldMap #-} + +instance Bitraversable Tagged where + bitraverse _ g (Tagged b) = Tagged <$> g b + {-# INLINE bitraverse #-} +#endif + +#ifdef MIN_VERSION_deepseq +instance NFData b => NFData (Tagged s b) where + rnf (Tagged b) = rnf b +#endif + +#ifdef MIN_VERSION_transformers +# if MIN_VERSION_transformers(0,4,0) && !(MIN_VERSION_transformers(0,5,0)) +instance Eq1 (Tagged s) where + eq1 = (==) + +instance Ord1 (Tagged s) where + compare1 = compare + +instance Read1 (Tagged s) where + readsPrec1 = readsPrec + +instance Show1 (Tagged s) where + showsPrec1 = showsPrec +# else +instance Eq1 (Tagged s) where + liftEq eq (Tagged a) (Tagged b) = eq a b + +instance Ord1 (Tagged s) where + liftCompare cmp (Tagged a) (Tagged b) = cmp a b + +instance Read1 (Tagged s) where + liftReadsPrec rp _ d = readParen (d > 10) $ \r -> + [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] + +instance Show1 (Tagged s) where + liftShowsPrec sp _ n (Tagged b) = showParen (n > 10) $ + showString "Tagged " . + sp 11 b + +instance Eq2 Tagged where + liftEq2 _ eq (Tagged a) (Tagged b) = eq a b + +instance Ord2 Tagged where + liftCompare2 _ cmp (Tagged a) (Tagged b) = cmp a b + +instance Read2 Tagged where + liftReadsPrec2 _ _ rp _ d = readParen (d > 10) $ \r -> + [(Tagged a, t) | ("Tagged", s) <- lex r, (a, t) <- rp 11 s] + +instance Show2 Tagged where + liftShowsPrec2 _ _ sp _ n (Tagged b) = showParen (n > 10) $ + showString "Tagged " . + sp 11 b +# endif +#endif + +instance Applicative (Tagged s) where + pure = Tagged + {-# INLINE pure #-} + Tagged f <*> Tagged x = Tagged (f x) + {-# INLINE (<*>) #-} + _ *> n = n + {-# INLINE (*>) #-} + +instance Monad (Tagged s) where + return = pure + {-# INLINE return #-} + Tagged m >>= k = k m + {-# INLINE (>>=) #-} + (>>) = (*>) + {-# INLINE (>>) #-} + +instance Foldable (Tagged s) where + foldMap f (Tagged x) = f x + {-# INLINE foldMap #-} + fold (Tagged x) = x + {-# INLINE fold #-} + foldr f z (Tagged x) = f x z + {-# INLINE foldr #-} + foldl f z (Tagged x) = f z x + {-# INLINE foldl #-} + foldl1 _ (Tagged x) = x + {-# INLINE foldl1 #-} + foldr1 _ (Tagged x) = x + {-# INLINE foldr1 #-} + +instance Traversable (Tagged s) where + traverse f (Tagged x) = Tagged <$> f x + {-# INLINE traverse #-} + sequenceA (Tagged x) = Tagged <$> x + {-# INLINE sequenceA #-} + mapM f (Tagged x) = liftM Tagged (f x) + {-# INLINE mapM #-} + sequence (Tagged x) = liftM Tagged x + {-# INLINE sequence #-} + +instance Enum a => Enum (Tagged s a) where + succ = fmap succ + pred = fmap pred + toEnum = Tagged . toEnum + fromEnum (Tagged x) = fromEnum x + enumFrom (Tagged x) = map Tagged (enumFrom x) + enumFromThen (Tagged x) (Tagged y) = map Tagged (enumFromThen x y) + enumFromTo (Tagged x) (Tagged y) = map Tagged (enumFromTo x y) + enumFromThenTo (Tagged x) (Tagged y) (Tagged z) = + map Tagged (enumFromThenTo x y z) + +instance Num a => Num (Tagged s a) where + (+) = liftA2 (+) + (-) = liftA2 (-) + (*) = liftA2 (*) + negate = fmap negate + abs = fmap abs + signum = fmap signum + fromInteger = Tagged . fromInteger + +instance Real a => Real (Tagged s a) where + toRational (Tagged x) = toRational x + +instance Integral a => Integral (Tagged s a) where + quot = liftA2 quot + rem = liftA2 rem + div = liftA2 div + mod = liftA2 mod + quotRem (Tagged x) (Tagged y) = (Tagged a, Tagged b) where + (a, b) = quotRem x y + divMod (Tagged x) (Tagged y) = (Tagged a, Tagged b) where + (a, b) = divMod x y + toInteger (Tagged x) = toInteger x + +instance Fractional a => Fractional (Tagged s a) where + (/) = liftA2 (/) + recip = fmap recip + fromRational = Tagged . fromRational + +instance Floating a => Floating (Tagged s a) where + pi = Tagged pi + exp = fmap exp + log = fmap log + sqrt = fmap sqrt + sin = fmap sin + cos = fmap cos + tan = fmap tan + asin = fmap asin + acos = fmap acos + atan = fmap atan + sinh = fmap sinh + cosh = fmap cosh + tanh = fmap tanh + asinh = fmap asinh + acosh = fmap acosh + atanh = fmap atanh + (**) = liftA2 (**) + logBase = liftA2 (**) + +instance RealFrac a => RealFrac (Tagged s a) where + properFraction (Tagged x) = (a, Tagged b) where + (a, b) = properFraction x + truncate (Tagged x) = truncate x + round (Tagged x) = round x + ceiling (Tagged x) = ceiling x + floor (Tagged x) = floor x + +instance RealFloat a => RealFloat (Tagged s a) where + floatRadix (Tagged x) = floatRadix x + floatDigits (Tagged x) = floatDigits x + floatRange (Tagged x) = floatRange x + decodeFloat (Tagged x) = decodeFloat x + encodeFloat m n = Tagged (encodeFloat m n) + exponent (Tagged x) = exponent x + significand = fmap significand + scaleFloat n = fmap (scaleFloat n) + isNaN (Tagged x) = isNaN x + isInfinite (Tagged x) = isInfinite x + isDenormalized (Tagged x) = isDenormalized x + isNegativeZero (Tagged x) = isNegativeZero x + isIEEE (Tagged x) = isIEEE x + atan2 = liftA2 atan2 + +instance Bits a => Bits (Tagged s a) where + Tagged a .&. Tagged b = Tagged (a .&. b) + Tagged a .|. Tagged b = Tagged (a .|. b) + xor (Tagged a) (Tagged b) = Tagged (xor a b) + complement (Tagged a) = Tagged (complement a) + shift (Tagged a) i = Tagged (shift a i) + shiftL (Tagged a) i = Tagged (shiftL a i) + shiftR (Tagged a) i = Tagged (shiftR a i) + rotate (Tagged a) i = Tagged (rotate a i) + rotateL (Tagged a) i = Tagged (rotateL a i) + rotateR (Tagged a) i = Tagged (rotateR a i) + bit i = Tagged (bit i) + setBit (Tagged a) i = Tagged (setBit a i) + clearBit (Tagged a) i = Tagged (clearBit a i) + complementBit (Tagged a) i = Tagged (complementBit a i) + testBit (Tagged a) i = testBit a i + isSigned (Tagged a) = isSigned a + bitSize (Tagged a) = bitSize a -- deprecated, but still required :( +#if __GLASGOW_HASKELL__ >= 704 + unsafeShiftL (Tagged a) i = Tagged (unsafeShiftL a i) + unsafeShiftR (Tagged a) i = Tagged (unsafeShiftR a i) + popCount (Tagged a) = popCount a +#endif +#if __GLASGOW_HASKELL__ >= 708 + bitSizeMaybe (Tagged a) = bitSizeMaybe a + zeroBits = Tagged zeroBits +#endif + +#if __GLASGOW_HASKELL__ >= 708 +instance FiniteBits a => FiniteBits (Tagged s a) where + finiteBitSize (Tagged a) = finiteBitSize a +# if __GLASGOW_HASKELL__ >= 710 + countLeadingZeros (Tagged a) = countLeadingZeros a + countTrailingZeros (Tagged a) = countTrailingZeros a +# endif +#endif + +instance IsString a => IsString (Tagged s a) where + fromString = Tagged . fromString + +instance Storable a => Storable (Tagged s a) where + sizeOf t = sizeOf a + where + Tagged a = Tagged undefined `asTypeOf` t + alignment t = alignment a + where + Tagged a = Tagged undefined `asTypeOf` t + peek ptr = Tagged <$> peek (castPtr ptr) + poke ptr (Tagged a) = poke (castPtr ptr) a + peekElemOff ptr i = Tagged <$> peekElemOff (castPtr ptr) i + pokeElemOff ptr i (Tagged a) = pokeElemOff (castPtr ptr) i a + peekByteOff ptr i = Tagged <$> peekByteOff (castPtr ptr) i + pokeByteOff ptr i (Tagged a) = pokeByteOff (castPtr ptr) i a + +-- | Some times you need to change the tag you have lying around. +-- Idiomatic usage is to make a new combinator for the relationship between the +-- tags that you want to enforce, and define that combinator using 'retag'. +-- +-- @ +-- data Succ n +-- retagSucc :: 'Tagged' n a -> 'Tagged' (Succ n) a +-- retagSucc = 'retag' +-- @ +retag :: Tagged s b -> Tagged t b +retag = Tagged . unTagged +{-# INLINE retag #-} + +-- | Alias for 'unTagged' +untag :: Tagged s b -> b +untag = unTagged + +-- | Tag a value with its own type. +tagSelf :: a -> Tagged a a +tagSelf = Tagged +{-# INLINE tagSelf #-} + +-- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second. +asTaggedTypeOf :: s -> tagged s b -> s +asTaggedTypeOf = const +{-# INLINE asTaggedTypeOf #-} + +witness :: Tagged a b -> a -> b +witness (Tagged b) _ = b +{-# INLINE witness #-} + +-- | 'untagSelf' is a type-restricted version of 'untag'. +untagSelf :: Tagged a a -> a +untagSelf (Tagged x) = x +{-# INLINE untagSelf #-} + +-- | Convert from a 'Tagged' representation to a representation +-- based on a 'Proxy'. +proxy :: Tagged s a -> proxy s -> a +proxy (Tagged x) _ = x +{-# INLINE proxy #-} + +-- | Convert from a representation based on a 'Proxy' to a 'Tagged' +-- representation. +unproxy :: (Proxy s -> a) -> Tagged s a +unproxy f = Tagged (f Proxy) +{-# INLINE unproxy #-} + +-- | Another way to convert a proxy to a tag. +tagWith :: proxy s -> a -> Tagged s a +tagWith _ = Tagged +{-# INLINE tagWith #-} + +-- | Some times you need to change the proxy you have lying around. +-- Idiomatic usage is to make a new combinator for the relationship +-- between the proxies that you want to enforce, and define that +-- combinator using 'reproxy'. +-- +-- @ +-- data Succ n +-- reproxySucc :: proxy n -> 'Proxy' (Succ n) +-- reproxySucc = 'reproxy' +-- @ +reproxy :: proxy a -> Proxy b +reproxy _ = Proxy diff --git a/stack-7.8.yaml b/stack-7.8.yaml new file mode 100644 index 0000000..6e73fc9 --- /dev/null +++ b/stack-7.8.yaml @@ -0,0 +1 @@ +resolver: lts-2.21 diff --git a/stack.yaml b/stack.yaml new file mode 100644 index 0000000..a194267 --- /dev/null +++ b/stack.yaml @@ -0,0 +1 @@ +resolver: nightly-2016-07-19 diff --git a/tagged.cabal b/tagged.cabal new file mode 100644 index 0000000..6bb6676 --- /dev/null +++ b/tagged.cabal @@ -0,0 +1,67 @@ +name: tagged +version: 0.8.5 +license: BSD3 +license-file: LICENSE +author: Edward A. Kmett +maintainer: Edward A. Kmett <[email protected]> +stability: experimental +category: Data, Phantom Types +synopsis: Haskell 98 phantom types to avoid unsafely passing dummy arguments +homepage: http://github.com/ekmett/tagged +bug-reports: http://github.com/ekmett/tagged/issues +copyright: 2009-2015 Edward A. Kmett +description: Haskell 98 phantom types to avoid unsafely passing dummy arguments +build-type: Simple +cabal-version: >= 1.10 +extra-source-files: .travis.yml CHANGELOG.markdown README.markdown HLint.hs + +source-repository head + type: git + location: git://github.com/ekmett/tagged.git + +flag deepseq + description: + You can disable the use of the `deepseq` package using `-f-deepseq`. + . + Disabing this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. + default: True + manual: True + +flag transformers + description: + You can disable the use of the `transformers` and `transformers-compat` packages using `-f-transformers`. + . + Disable this is an unsupported configuration, but it may be useful for accelerating builds in sandboxes for expert users. + default: True + manual: True + +library + default-language: Haskell98 + other-extensions: CPP + build-depends: base >= 2 && < 5 + ghc-options: -Wall + hs-source-dirs: src + exposed-modules: Data.Tagged + + if !impl(hugs) + cpp-options: -DLANGUAGE_DeriveDataTypeable + other-extensions: DeriveDataTypeable + + if impl(ghc<7.7) + hs-source-dirs: old + exposed-modules: Data.Proxy + other-modules: Paths_tagged + + if impl(ghc>=7.2 && <7.5) + build-depends: ghc-prim + + if impl(ghc>=7.6) + exposed-modules: Data.Proxy.TH + build-depends: template-haskell >= 2.8 && < 2.12 + + if flag(deepseq) + build-depends: deepseq >= 1.1 && < 1.5 + + if flag(transformers) + build-depends: transformers >= 0.2 && < 0.6, + transformers-compat >= 0.5 && < 1
willert/masonx-plugin-catalyst-importstash
72aa86e590818d09d5c45522b549001cc49e134b
Inital import
diff --git a/dist.ini b/dist.ini new file mode 100644 index 0000000..aa5de6c --- /dev/null +++ b/dist.ini @@ -0,0 +1,18 @@ +name = MasonX-Plugin-Catalyst-ImportStash +version = 0.01 +abstract = Import the stash into all components +author = Sebastian Willert <[email protected]> +license = Perl_5 +copyright_holder = Sebastian Willert + +[Prereq] +Test::More = 0.88 +HTML::Mason = 1.32 +MasonX::RequestContext::Catalyst = 0 + +[@Filter] +bundle = @Classic +remove = PodVersion +remove = BumpVersion + +[PodPurler] diff --git a/lib/MasonX/Plugin/Catalyst/ImportStash.pm b/lib/MasonX/Plugin/Catalyst/ImportStash.pm new file mode 100644 index 0000000..18d0a95 --- /dev/null +++ b/lib/MasonX/Plugin/Catalyst/ImportStash.pm @@ -0,0 +1,136 @@ +package MasonX::Plugin::Catalyst::ImportStash; +# ABSTRACT: Import the stash into all components + +use strict; +use warnings; + +use base qw(HTML::Mason::Plugin); + +=head1 SYNOPIS + + # in your action: + sub test : Local { + my ( $self, $ctx ) = @_; + $ctx->stash( deep_value => 'Foo' ); + } + + # in your request component (test.mhtml): + <h1>Calling deep value handler:</h1> + <& some_deep_value_handler, direct_value => 'Bar' &> + + # in some_deep_value_handler + <%args> + $direct_value + $deep_value + </%args> + <% $deep_value . $direct_value %> + <%doc> prints FooBar as expected </%doc> + +=head1 DESCRIPTION + +Mason components that are not in the wrapper chain (i.E. all components +except autohandlers and those called by C<$m->call_next>) don't get +an accessible copy of the request args. This makes sense when you are +using Mason as a stand-alone application provider and request args get +set according to the HTTP request and thus are totally uncontrollable, +and all model and controller functionallity tends to be placed near the +hand-off. + +In a Catalyst context this is cumbersome: you control the args +passed to Mason anyways and value retrieval happens far from the call to +the resp. component that will act as view for them. This plugin tries to +make things a little more pleasant in providing all components (excluding +subcomponents) with a copy of all non-private stash variables as args. + +=cut + +my $interface_check_done; + +sub start_request_hook { + my ( $self, $context ) = @_; + + unless ( $interface_check_done ) { + my $meta = eval{ Class::MOP::class_of( $self->request_class )}; + my $api_ok = $meta&&$meta->does_role('MasonX::RequestContext::Catalyst'); + die ref($self) . " needs a MasonX::RequestContext::Catalyst enabled " . + "request instance to work properly" unless $api_ok; + $interface_check_done = 1; + } + + # get (another!) copy of all non-private values in the stash + my $stash = $context->request->catalyst_ctx->stash; + my @sargs = map{ $_ => $stash->{$_} } grep{!/^_/} keys %$stash; + + # prepare the notes we will use during this request + $context->request->notes( '__mp_cis_stash', \@sargs ); + $context->request->notes( '__mp_cis_modified_comps', {} ) + unless defined $context->request->notes( '__mp_cis_modified_comps' ); + +} + +sub start_component_hook { + my ($self, $context) = @_; + my $comp = $context->comp; + + # ignore subcomponents + return if $comp->is_subcomp; + + # components in the call chain already + # get all request args and thus the stash + return if exists $context->request->{wrapper_index}{ $comp->comp_id }; + + # do nothing if the resp. conponent isn't + # interested in named arguments + return unless %{ $comp->declared_args }; + + my $sargs = $context->request->notes( '__mp_cis_stash' ); + + # mark this component so we can restore the arg list later on + $context->request->notes( '__mp_cis_modified_comps' )->{ $comp } = 1; + + unshift @{ $context->args }, @{ $sargs }; + +} + +sub end_component_hook { + my ( $self, $context ) = @_; + my $comp = $context->comp; + + # fetch and unset components modification status from + # request notes, return if there is nothing to do + delete $context->request->notes( '__mp_cis_modified_comps' )->{$comp} + or return; + + my $sargs = $context->request->notes( '__mp_cis_stash' ); + + # remove stash from argument list (this is fatal if a component + # has mucked around with the aliased @_ while also using named + # arguments, but anyone doing this doesn't deserve better) + splice @{ $context->request->args }, 0, scalar @$sargs; + +} + +sub end_request_hook { + my ( $self, $context ) = @_; + # in theory these should die with the current request, but I + # still want to unset them explicitly here to avoid potential + # circular references + $context->request->notes( '__mp_cis_stash', undef ); + $context->request->notes( '__mp_cis_modified_comps', undef ) +} + +1; + +__END__ + +=head1 CAVEATS + +Although L<HTML::Mason::Plugin> warns that a plugin may NOT modify args, +I have had no problems at all with at least five low to medium profile +websites in production. Consider yourself warned, nontheless! + +Do not use named parameters in conjunction with modifying @_ in your +components. Not that this needed to be mentioned, $deity kills a +kitten everytime you do so, anyways. + +=cut diff --git a/t/00-loading.t b/t/00-loading.t new file mode 100644 index 0000000..c96b765 --- /dev/null +++ b/t/00-loading.t @@ -0,0 +1,12 @@ +use Test::More; + +use FindBin; +use lib "$FindBin::Bin/../lib"; + +sub use_ok_or_bail($) { + use_ok $_[0] or BAIL_OUT( "Failed to load essential module $_[0]" ); +} + +use_ok_or_bail 'MasonX::Plugin::Catalyst::ImportStash'; + +done_testing();
samsoir/kohana-gravatar
550954cb717c6f521d950ae94255727559ead137
Fixed config loading issue
diff --git a/classes/kohana/gravatar.php b/classes/kohana/gravatar.php index 12ee5f0..48c6f9e 100644 --- a/classes/kohana/gravatar.php +++ b/classes/kohana/gravatar.php @@ -1,282 +1,282 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [Gravatar's](http://en.gravatar.com) are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * @see http://en.gravatar.com * @package Kohana * @category Gravatar * @version 3.1.0 * @author Kohana Team * @copyright (c) 2009-2010 Kohana Team * @license http://kohanaphp.com/license */ class Kohana_Gravatar { const GRAVATAR_G = 'G'; const GRAVATAR_PG = 'PG'; const GRAVATAR_R = 'R'; const GRAVATAR_X = 'X'; /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) { self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); } // Return a the instance return self::$_instances[$email][$config_checksum]; } /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array */ public $attributes = array(); /** * The email address of the user * * @var string */ public $email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Kohana_Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address $this->email = $email; if (empty($config)) { $this->_config = Kohana::$config->load('gravatar.default'); } elseif (is_array($config)) { // Setup the configuration - $config += Kohana::config('gravatar.default'); + $config += Kohana::$config->load('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { - if ($config = Kohana::config('gravatar.'.$config) === NULL) + if ($config = Kohana::$config->load('gravatar.'.$config) === NULL) { throw new Kohana_Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); } - $this->_config = $config + Kohana::config('gravatar.default'); + $this->_config = $config + Kohana::$config->load('gravatar.default'); } } /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self */ public function size($size = NULL) { if ($size === NULL) { return $this->_config['size']; } else { $this->_config['size'] = (int) $size; return $this; } } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self * @throws Kohana_Gravatar_Exception */ public function rating($rating = NULL) { $rating = strtoupper($rating); if ($rating === NULL) { return $this->_config['rating']; } else { if (in_array($rating, array(Gravatar::GRAVATAR_G, Gravatar::GRAVATAR_PG, Gravatar::GRAVATAR_R, Gravatar::GRAVATAR_X))) { $this->_config['rating'] = $rating; } else { throw new Kohana_Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); } } return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self */ public function default_image($url = NULL) { if ($url === NULL) { return $this->_config['default']; } else { if (validate::url($url)) { $this->_config['default'] = $url; } else { throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); } } return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public */ public function render($view = FALSE, $email = NULL) { if ($email !== NULL) { $this->email = $email; } $data = array('attr' => array(), 'src' => $this->_generate_url()); if ($this->attributes) { $data['attr'] += $this->attributes; } $data['attr']['alt'] = $this->_process_alt(); if ( ! $view) { return new View($this->_config['view'], $data); } else { return new View($view, $data); } } /** * Process the alt attribute output * * @return string * @access protected */ protected function _process_alt() { $keys = array ( '{$email}' => $this->email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) { $alt = strtr($this->_config['alt'], $keys); } else { $alt = FALSE; } return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected */ protected function _generate_url() { $string = $this->_config['service']. '?gravatar_id='.md5($this->email). '&s='.$this->_config['size']. '&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) { $string .= '&d='.$this->_config['default']; } return $string; } } \ No newline at end of file
samsoir/kohana-gravatar
dd0d8119ea61b97ee46ff90883d68203145809c7
Fixed config issue with Kohana 3.2
diff --git a/classes/kohana/gravatar.php b/classes/kohana/gravatar.php index 500fd78..12ee5f0 100644 --- a/classes/kohana/gravatar.php +++ b/classes/kohana/gravatar.php @@ -1,282 +1,282 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [Gravatar's](http://en.gravatar.com) are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * @see http://en.gravatar.com * @package Kohana * @category Gravatar * @version 3.1.0 * @author Kohana Team * @copyright (c) 2009-2010 Kohana Team * @license http://kohanaphp.com/license */ class Kohana_Gravatar { const GRAVATAR_G = 'G'; const GRAVATAR_PG = 'PG'; const GRAVATAR_R = 'R'; const GRAVATAR_X = 'X'; /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) { self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); } // Return a the instance return self::$_instances[$email][$config_checksum]; } /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array */ public $attributes = array(); /** * The email address of the user * * @var string */ public $email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Kohana_Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address $this->email = $email; if (empty($config)) { - $this->_config = Kohana::config('gravatar.default'); + $this->_config = Kohana::$config->load('gravatar.default'); } elseif (is_array($config)) { // Setup the configuration $config += Kohana::config('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { if ($config = Kohana::config('gravatar.'.$config) === NULL) { throw new Kohana_Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); } $this->_config = $config + Kohana::config('gravatar.default'); } } /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self */ public function size($size = NULL) { if ($size === NULL) { return $this->_config['size']; } else { $this->_config['size'] = (int) $size; return $this; } } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self * @throws Kohana_Gravatar_Exception */ public function rating($rating = NULL) { $rating = strtoupper($rating); if ($rating === NULL) { return $this->_config['rating']; } else { if (in_array($rating, array(Gravatar::GRAVATAR_G, Gravatar::GRAVATAR_PG, Gravatar::GRAVATAR_R, Gravatar::GRAVATAR_X))) { $this->_config['rating'] = $rating; } else { throw new Kohana_Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); } } return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self */ public function default_image($url = NULL) { if ($url === NULL) { return $this->_config['default']; } else { if (validate::url($url)) { $this->_config['default'] = $url; } else { throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); } } return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public */ public function render($view = FALSE, $email = NULL) { if ($email !== NULL) { $this->email = $email; } $data = array('attr' => array(), 'src' => $this->_generate_url()); if ($this->attributes) { $data['attr'] += $this->attributes; } $data['attr']['alt'] = $this->_process_alt(); if ( ! $view) { return new View($this->_config['view'], $data); } else { return new View($view, $data); } } /** * Process the alt attribute output * * @return string * @access protected */ protected function _process_alt() { $keys = array ( '{$email}' => $this->email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) { $alt = strtr($this->_config['alt'], $keys); } else { $alt = FALSE; } return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected */ protected function _generate_url() { $string = $this->_config['service']. '?gravatar_id='.md5($this->email). '&s='.$this->_config['size']. '&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) { $string .= '&d='.$this->_config['default']; } return $string; } } \ No newline at end of file
samsoir/kohana-gravatar
1659d2565dca8a33c9bd5847a40fe6773672c9a3
fixing typo, should be attr not alt
diff --git a/views/gravatar/image.php b/views/gravatar/image.php index d6a32bc..7b798f0 100644 --- a/views/gravatar/image.php +++ b/views/gravatar/image.php @@ -1 +1 @@ -<?php echo html::image($src, $alt); ?> \ No newline at end of file +<?php echo html::image($src, $attr); ?> \ No newline at end of file
samsoir/kohana-gravatar
ad24e9fdbd13bb161f054ab29db68d27031d206e
fixing typo
diff --git a/views/gravatar/image.php b/views/gravatar/image.php index d6a32bc..7b798f0 100644 --- a/views/gravatar/image.php +++ b/views/gravatar/image.php @@ -1 +1 @@ -<?php echo html::image($src, $alt); ?> \ No newline at end of file +<?php echo html::image($src, $attr); ?> \ No newline at end of file
samsoir/kohana-gravatar
4f2321d4d2eb3d940f744fcfa96878f0e29d1157
Refactored the gravatar library to use Kohana based namespacing
diff --git a/classes/gravatar.php b/classes/gravatar.php index 901e90c..ab03044 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -1,282 +1,3 @@ <?php defined('SYSPATH') or die('No direct script access.'); -/** - * [Gravatar's](http://en.gravatar.com) are universal avatars available to all web sites and services. - * Users must register their email addresses with Gravatar before their avatars will be - * usable with this module. Users with gravatars can have a default image of your selection. - * - * @package Gravatar for Kohana PHP 3 - * @author The Kohana Team - * @copyright Copyright (c) 2009-2010 Kohana - * @version 3.1.0 - * @license Kohana License http://kohanaframework.org/license - */ -class Gravatar { - const GRAVATAR_G = 'G'; - const GRAVATAR_PG = 'PG'; - const GRAVATAR_R = 'R'; - const GRAVATAR_X = 'X'; - - /** - * Static instances - * - * @var array - * @static - * @access protected - */ - static protected $_instances = array(); - - /** - * Instance constructor pattern - * - * @param string email the Gravatar to fetch for email address - * @param string config the name of the configuration grouping - * @param array config array of key value configuration pairs - * @return Gravatar - * @access public - * @static - */ - public static function instance($email, $config = NULL) - { - // Create an instance checksum - $config_checksum = sha1(serialize($config)); - - // Load the Gravatar instance for email and configuration - if ( ! isset(self::$_instances[$email][$config_checksum])) - { - self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); - } - - // Return a the instance - return self::$_instances[$email][$config_checksum]; - } - - /** - * Configuration for this library, merged with the static config - * - * @var array - * @access protected - */ - protected $_config; - - /** - * Additional attributes to add to the image - * - * @var array - */ - public $attributes = array(); - - /** - * The email address of the user - * - * @var string - */ - public $email; - - /** - * Gravatar constructor - * - * @param string email the Gravatar to fetch for email address - * @param string config the name of the configuration grouping - * @param array config array of key value configuration pairs - * @access public - * @throws Gravatar_Exception - */ - protected function __construct($email, $config = NULL) - { - // Set the email address - $this->email = $email; - - if (empty($config)) - { - $this->_config = Kohana::config('gravatar.default'); - } - elseif (is_array($config)) - { - // Setup the configuration - $config += Kohana::config('gravatar.default'); - $this->_config = $config; - } - elseif (is_string($config)) - { - if ($config = Kohana::config('gravatar.'.$config) === NULL) - { - throw new Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); - } - - $this->_config = $config + Kohana::config('gravatar.default'); - } - } - - /** - * Handles this object being cast to string - * - * @return string the resulting Gravatar - * @access public - * @author Sam Clark - */ - public function __toString() - { - return (string) $this->render(); - } - - /** - * Accessor method for setting size of gravatar - * - * @param int size the size of the gravatar image in pixels - * @return self - */ - public function size($size = NULL) - { - if ($size === NULL) - { - return $this->_config['size']; - } - else - { - $this->_config['size'] = (int) $size; - return $this; - } - } - - /** - * Accessor method for the rating of the gravatar - * - * @param string rating the rating of the gravatar - * @return self - */ - public function rating($rating = NULL) - { - $rating = strtoupper($rating); - - if ($rating === NULL) - { - return $this->_config['rating']; - } - else - { - if (in_array($rating, array(Gravatar::GRAVATAR_G, Gravatar::GRAVATAR_PG, Gravatar::GRAVATAR_R, Gravatar::GRAVATAR_X))) - { - $this->_config['rating'] = $rating; - } - else - { - throw new Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); - } - } - - return $this; - } - - /** - * Accessor method for setting the default image if the supplied email address or rating return an empty result - * - * @param string url the url of the image to use instead of the Gravatar - * @return self - */ - public function default_image($url = NULL) - { - if ($url === NULL) - { - return $this->_config['default']; - } - else - { - if (validate::url($url)) - { - $this->_config['default'] = $url; - } - else - { - throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); - } - } - - return $this; - } - - /** - * Renders the Gravatar using supplied configuration and attributes. Can use custom view. - * - * @param string view [Optional] a kohana PHP - * @param string email [Optional] the valid email of a Gravatar user - * @return string the rendered Gravatar output - * @access public - * @author Sam Clark - */ - public function render($view = FALSE, $email = NULL) - { - if ($email !== NULL) - { - $this->email = $email; - } - - $data = array('attr' => array(), 'src' => $this->_generate_url()); - - if ($this->attributes) - { - $data['attr'] += $this->attributes; - } - - $data['attr']['alt'] = $this->_process_alt(); - - if ( ! $view) - { - return new View($this->_config['view'], $data); - } - else - { - return new View($view, $data); - } - } - - /** - * Process the alt attribute output - * - * @return string - * @access protected - * @author Sam Clark - */ - protected function _process_alt() - { - $keys = array - ( - '{$email}' => $this->email, - '{$size}' => $this->_config['size'], - '{$rating}' => $this->_config['rating'], - ); - - if ($this->_config['alt']) - { - $alt = strtr($this->_config['alt'], $keys); - } - else - { - $alt = FALSE; - } - - return $alt; - } - - /** - * Creates the Gravatar URL based on the configuration and email - * - * @return string the resulting Gravatar URL - * @access protected - * @author Sam Clark - */ - protected function _generate_url() - { - $string = $this->_config['service']. - '?gravatar_id='.md5($this->email). - '&s='.$this->_config['size']. - '&r='.$this->_config['rating']; - - if ( ! empty($this->_config['default'])) - { - $string .= '&d='.$this->_config['default']; - } - - return $string; - } -} \ No newline at end of file +class Gravatar extends Kohana_Gravatar {} \ No newline at end of file diff --git a/classes/gravatar/exception.php b/classes/gravatar/exception.php deleted file mode 100644 index 7a4e4d1..0000000 --- a/classes/gravatar/exception.php +++ /dev/null @@ -1,3 +0,0 @@ -<?php defined('SYSPATH') or die('No direct script access.'); - -class Gravatar_Exception extends Kohana_Exception { } \ No newline at end of file diff --git a/classes/gravatar/xmlrpc.php b/classes/gravatar/xmlrpc.php index 6139d93..e3cbea9 100644 --- a/classes/gravatar/xmlrpc.php +++ b/classes/gravatar/xmlrpc.php @@ -1,304 +1,3 @@ <?php defined('SYSPATH') or die('No direct script access.'); -/** - * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. - * Users must register their email addresses with Gravatar before their avatars will be - * usable with this module. Users with gravatars can have a default image of your selection. - * - * [ref-gravatar]: http://en.gravatar.com/ - * - * @package Gravatar XMLRPC API for Kohana PHP 3 - * @requires PHP-SOAP - * @author Sam C. De Freyssinet - * @copyright (c) 2009 De Freyssinet - * @version 3.0.0 - * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ - */ -class Gravatar_Xmlrpc { - /** - * Gravatar Ratings constants - */ - const G = 0; - const PG = 1; - const R = 2; - const X = 3; - - - /** - * Create an instance of the Gravatar XMLRPC API client - * - * @param array $config - * @return Gravatar_Xmlrpc - * @access public - */ - public static function factory($config = array()) - { - return new Gravatar_Xmlrpc($config); - } - - /** - * @var array - */ - protected $_config; - - /** - * Constructor - * - * @param array $config - */ - public function __construct($config) - { - // Check for soap - if ( ! extension_loaded('XMLRPC')) - { - throw new Gravatar_Xmlrpc_Exception('XML-RPC extension must be loaded to use this class!'); - } - - // Configure this library - $config += Kohana::config('gravatar.xmlrpc'); - $this->_config = $config; - } - - /** - * Set or get the password - * - * @param string $password - * @return mixed - */ - public function password($password = NULL) - { - // If there is no API key supplied - if ($password === NULL) - { - return $this->_config['password']; - } - - // Else set the API key - $this->_config['password'] = (string) $password; - - // Return this - return $this; - } - - /** - * Set or get the email address in question - * - * @param string $email [Optional] - * @return mixed - */ - public function email($email = NULL) - { - // If no argument, return the email address - if ($email === NULL) - { - return $this->_config['email']; - } - - // Set the email address - $this->_config['email']; - - // Return this - return $this; - } - - /** - * Checks that a hash exists - * - * @param array $hashes - * @return array - */ - public function exists(array $hashes) - { - return $this->_xmlrpc_request('grav.exists', array('hashes' => $hashes)); - } - - /** - * Returns an array of email addresses - * registered to the account API key - * - * @return array - */ - public function addresses() - { - return $this->_xmlrpc_request('grav.addresses'); - } - - /** - * Returns an array containing images - * registered to this user - and their - * respective rating - * - * @return array - */ - public function user_images() - { - return $this->_xmlrpc_request('grav.userimages'); - } - - /** - * Save an image to the registered account. - * Images must be transferred in raw base64 - * encoded format. - * - * @param string $image - * @param int $rating [Optional] - * @return string|boolean - */ - public function save_data($image, $rating = NULL) - { - // Load the image - if ( ! $resource = file_get_contents($image)) - { - throw new Gravatar_Xmlrpc_Exception(__METHOD__.' unable to open image : :file', array(':file' => $image)); - } - - // If no rating has been applied, use general - if ($rating === NULL) - { - $rating = Gravatar_Xmlrpc::G; - } - - // Encode the image resource - $encoded_image = base64_encode($resource); - - // Save the image to Gravatar - return $this->_xmlrpc_request('grav.saveData', array('data' => $encoded_image, 'rating' => $rating)); - } - - /** - * Save a image URL to the registered account. - * - * @param string $url - * @param int $rating [Optional] - * @return string|boolean - */ - public function save_url($url, $rating = NULL) - { - // If the URL supplied is not valid - if ( ! Validate::url($url)) - { - // Throw an exception - throw new Gravatar_Xmlrpc_Exception(__METHOD__.' invalid URL supplied : :url', array(':url' => $url)); - } - - // If no rating has been applied, use general - if ($rating === NULL) - { - $rating = Gravatar_Xmlrpc::G; - } - - // Save the image to Gravatar - return $this->_xmlrpc_request('grav.saveData', array('url' => $url, 'rating' => $rating)); - } - - /** - * Assign a user image on Gravatar to the addresses - * supplied. - * - * @param string user_image - * @param array addresses - * @return array - */ - public function use_user_image($user_image, array $addresses) - { - // Set the userimage to all supplied addresses - return $this->_xmlrpc_request('grav.useUserimage', array('userImage' => $user_image, 'addresses' => $addresses)); - } - - /** - * Remove the userimage associated with one or more email addresses - * - * @param array addresses - * @return boolean - */ - public function remove_image(array $addresses) - { - // Remove the current image from the supplied addresses - return $this->_xmlrpc_request('grav.removeImage', array('addresses' => $addresses)); - } - - /** - * Remove a user image from the account and any email addresses with which it is associated - * - * @param string user_image - * @return boolean - */ - public function delete_user_image($user_image) - { - // Delete an image from the account - return $this->_xmlrpc_request('grav.deleteUserimage', array('userimage' => $user_image)); - } - - /** - * Processes an XML-RPC response based on the method and parameters passed - * to it. This method uses PHP streams over cURL, which makes it available - * to the vast majority of systems. - * - * @param string method - * @param array parameters - * @return mixed - */ - protected function _xmlrpc_request($method, array $parameters = array()) - { - // Create the endpoint - $endpoint = $this->_prepare_service_endpoint(); - - // Apply the Gravatar user password to the parameters - $parameters['password'] = $this->_config['password']; - - // Create the XML-RPC request - $xml_payload = xmlrpc_encode_request($method, $parameters); - - // Create a context stream, enforcing a POST request with correct header - $context = stream_context_create(array( - 'http' => array( - 'method' => 'POST', - 'header' => 'Content-Type: text/xml', - 'content' => $xml_payload - ) - )); - - try - { - // Process the XML-RPC request and decode the response - $xmlrpc_response = xmlrpc_decode(file_get_contents($endpoint, FALSE, $context)); - - // If there was an error - if ($xmlrpc_response and xmlrpc_is_fault($xmlrpc_response)) - { - // Throw an exception - throw new Gravatar_Xmlrpc_Exception($xmlrpc_response['faultString'], NULL, $xmlrpc_response['faultCode']); - } - else - { - // return the response - return $xmlrpc_response; - } - - // Shouldn't get this far - throw new Gravatar_Xmlrpc_Exception(__METHOD__.' something went wrong, xmlrpc_response was empty'); - } - // Catch all unexpected exceptions - catch (Exception $e) - { - throw new Gravatar_Xmlrpc_Exception($e->getMessage(), NULL, $e->getCode()); - } - } - - /** - * Execute the Xmlrpc request and return - * the result - * - * @return mixed - */ - protected function _prepare_service_endpoint() - { - if ($this->_config['email'] === NULL) - { - throw new Gravatar_Xmlrpc_Exception('Username must be supplied to perform Gravatar API requests!'); - } - - // Generate full uri with user id - return $this->_config['service'].'?user='.md5($this->_config['email']); - } -} \ No newline at end of file +class Gravatar_Xmlrpc extends Kohana_Gravatar_Xmlrpc {} \ No newline at end of file diff --git a/classes/gravatar/xmlrpc/exception.php b/classes/gravatar/xmlrpc/exception.php deleted file mode 100644 index 561a47c..0000000 --- a/classes/gravatar/xmlrpc/exception.php +++ /dev/null @@ -1,3 +0,0 @@ -<?php defined('SYSPATH') or die('No direct script access.'); - -class Gravatar_Xmlrpc_Exception extends Gravatar_Exception {} diff --git a/classes/kohana/gravatar.php b/classes/kohana/gravatar.php new file mode 100644 index 0000000..500fd78 --- /dev/null +++ b/classes/kohana/gravatar.php @@ -0,0 +1,282 @@ +<?php defined('SYSPATH') or die('No direct script access.'); +/** + * [Gravatar's](http://en.gravatar.com) are universal avatars available to all web sites and services. + * Users must register their email addresses with Gravatar before their avatars will be + * usable with this module. Users with gravatars can have a default image of your selection. + * + * @see http://en.gravatar.com + * @package Kohana + * @category Gravatar + * @version 3.1.0 + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Gravatar { + + const GRAVATAR_G = 'G'; + const GRAVATAR_PG = 'PG'; + const GRAVATAR_R = 'R'; + const GRAVATAR_X = 'X'; + + /** + * Static instances + * + * @var array + * @static + * @access protected + */ + static protected $_instances = array(); + + /** + * Instance constructor pattern + * + * @param string email the Gravatar to fetch for email address + * @param string config the name of the configuration grouping + * @param array config array of key value configuration pairs + * @return Gravatar + * @access public + * @static + */ + public static function instance($email, $config = NULL) + { + // Create an instance checksum + $config_checksum = sha1(serialize($config)); + + // Load the Gravatar instance for email and configuration + if ( ! isset(self::$_instances[$email][$config_checksum])) + { + self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); + } + + // Return a the instance + return self::$_instances[$email][$config_checksum]; + } + + /** + * Configuration for this library, merged with the static config + * + * @var array + * @access protected + */ + protected $_config; + + /** + * Additional attributes to add to the image + * + * @var array + */ + public $attributes = array(); + + /** + * The email address of the user + * + * @var string + */ + public $email; + + /** + * Gravatar constructor + * + * @param string email the Gravatar to fetch for email address + * @param string config the name of the configuration grouping + * @param array config array of key value configuration pairs + * @access public + * @throws Kohana_Gravatar_Exception + */ + protected function __construct($email, $config = NULL) + { + // Set the email address + $this->email = $email; + + if (empty($config)) + { + $this->_config = Kohana::config('gravatar.default'); + } + elseif (is_array($config)) + { + // Setup the configuration + $config += Kohana::config('gravatar.default'); + $this->_config = $config; + } + elseif (is_string($config)) + { + if ($config = Kohana::config('gravatar.'.$config) === NULL) + { + throw new Kohana_Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); + } + + $this->_config = $config + Kohana::config('gravatar.default'); + } + } + + /** + * Handles this object being cast to string + * + * @return string the resulting Gravatar + * @access public + * @author Sam Clark + */ + public function __toString() + { + return (string) $this->render(); + } + + /** + * Accessor method for setting size of gravatar + * + * @param int size the size of the gravatar image in pixels + * @return self + */ + public function size($size = NULL) + { + if ($size === NULL) + { + return $this->_config['size']; + } + else + { + $this->_config['size'] = (int) $size; + return $this; + } + } + + /** + * Accessor method for the rating of the gravatar + * + * @param string rating the rating of the gravatar + * @return self + * @throws Kohana_Gravatar_Exception + */ + public function rating($rating = NULL) + { + $rating = strtoupper($rating); + + if ($rating === NULL) + { + return $this->_config['rating']; + } + else + { + if (in_array($rating, array(Gravatar::GRAVATAR_G, Gravatar::GRAVATAR_PG, Gravatar::GRAVATAR_R, Gravatar::GRAVATAR_X))) + { + $this->_config['rating'] = $rating; + } + else + { + throw new Kohana_Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); + } + } + + return $this; + } + + /** + * Accessor method for setting the default image if the supplied email address or rating return an empty result + * + * @param string url the url of the image to use instead of the Gravatar + * @return self + */ + public function default_image($url = NULL) + { + if ($url === NULL) + { + return $this->_config['default']; + } + else + { + if (validate::url($url)) + { + $this->_config['default'] = $url; + } + else + { + throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); + } + } + + return $this; + } + + /** + * Renders the Gravatar using supplied configuration and attributes. Can use custom view. + * + * @param string view [Optional] a kohana PHP + * @param string email [Optional] the valid email of a Gravatar user + * @return string the rendered Gravatar output + * @access public + */ + public function render($view = FALSE, $email = NULL) + { + if ($email !== NULL) + { + $this->email = $email; + } + + $data = array('attr' => array(), 'src' => $this->_generate_url()); + + if ($this->attributes) + { + $data['attr'] += $this->attributes; + } + + $data['attr']['alt'] = $this->_process_alt(); + + if ( ! $view) + { + return new View($this->_config['view'], $data); + } + else + { + return new View($view, $data); + } + } + + /** + * Process the alt attribute output + * + * @return string + * @access protected + */ + protected function _process_alt() + { + $keys = array + ( + '{$email}' => $this->email, + '{$size}' => $this->_config['size'], + '{$rating}' => $this->_config['rating'], + ); + + if ($this->_config['alt']) + { + $alt = strtr($this->_config['alt'], $keys); + } + else + { + $alt = FALSE; + } + + return $alt; + } + + /** + * Creates the Gravatar URL based on the configuration and email + * + * @return string the resulting Gravatar URL + * @access protected + */ + protected function _generate_url() + { + $string = $this->_config['service']. + '?gravatar_id='.md5($this->email). + '&s='.$this->_config['size']. + '&r='.$this->_config['rating']; + + if ( ! empty($this->_config['default'])) + { + $string .= '&d='.$this->_config['default']; + } + + return $string; + } +} \ No newline at end of file diff --git a/classes/kohana/gravatar/exception.php b/classes/kohana/gravatar/exception.php new file mode 100644 index 0000000..c2bb720 --- /dev/null +++ b/classes/kohana/gravatar/exception.php @@ -0,0 +1,10 @@ +<?php defined('SYSPATH') or die('No direct script access.'); +/** + * @package Kohana + * @category Gravatar + * @version 3.1.0 + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Gravatar_Exception extends Kohana_Exception { } \ No newline at end of file diff --git a/classes/kohana/gravatar/xmlrpc.php b/classes/kohana/gravatar/xmlrpc.php new file mode 100644 index 0000000..cb22c9b --- /dev/null +++ b/classes/kohana/gravatar/xmlrpc.php @@ -0,0 +1,309 @@ +<?php defined('SYSPATH') or die('No direct script access.'); +/** + * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. + * Users must register their email addresses with Gravatar before their avatars will be + * usable with this module. Users with gravatars can have a default image of your selection. + * + * @see http://en.gravatar.com/ + * + * @package Kohana + * @category Gravatar + * @version 3.1.0 + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Gravatar_Xmlrpc { + + /** + * Gravatar Ratings constants + */ + const G = 0; + const PG = 1; + const R = 2; + const X = 3; + + + /** + * Create an instance of the Gravatar XMLRPC API client + * + * @param array $config + * @return Gravatar_Xmlrpc + * @access public + */ + public static function factory($config = array()) + { + return new Gravatar_Xmlrpc($config); + } + + /** + * @var array + */ + protected $_config; + + /** + * Constructor + * + * @param array $config + * @throws Kohana_Gravatar_Xmlrpc_Exception + */ + public function __construct($config) + { + // Check for soap + if ( ! extension_loaded('XMLRPC')) + { + throw new Kohana_Gravatar_Xmlrpc_Exception('XML-RPC extension must be loaded to use this class!'); + } + + // Configure this library + $config += Kohana::config('gravatar.xmlrpc'); + $this->_config = $config; + } + + /** + * Set or get the password + * + * @param string $password + * @return mixed + */ + public function password($password = NULL) + { + // If there is no API key supplied + if ($password === NULL) + { + return $this->_config['password']; + } + + // Else set the API key + $this->_config['password'] = (string) $password; + + // Return this + return $this; + } + + /** + * Set or get the email address in question + * + * @param string $email [Optional] + * @return mixed + */ + public function email($email = NULL) + { + // If no argument, return the email address + if ($email === NULL) + { + return $this->_config['email']; + } + + // Set the email address + $this->_config['email']; + + // Return this + return $this; + } + + /** + * Checks that a hash exists + * + * @param array $hashes + * @return array + */ + public function exists(array $hashes) + { + return $this->_xmlrpc_request('grav.exists', array('hashes' => $hashes)); + } + + /** + * Returns an array of email addresses + * registered to the account API key + * + * @return array + */ + public function addresses() + { + return $this->_xmlrpc_request('grav.addresses'); + } + + /** + * Returns an array containing images + * registered to this user - and their + * respective rating + * + * @return array + */ + public function user_images() + { + return $this->_xmlrpc_request('grav.userimages'); + } + + /** + * Save an image to the registered account. + * Images must be transferred in raw base64 + * encoded format. + * + * @param string $image + * @param int $rating [Optional] + * @return string|boolean + * @throws Kohana_Gravatar_Xmlrpc_Exception + */ + public function save_data($image, $rating = NULL) + { + // Load the image + if ( ! $resource = file_get_contents($image)) + { + throw new Kohana_Gravatar_Xmlrpc_Exception(__METHOD__.' unable to open image : :file', array(':file' => $image)); + } + + // If no rating has been applied, use general + if ($rating === NULL) + { + $rating = Gravatar_Xmlrpc::G; + } + + // Encode the image resource + $encoded_image = base64_encode($resource); + + // Save the image to Gravatar + return $this->_xmlrpc_request('grav.saveData', array('data' => $encoded_image, 'rating' => $rating)); + } + + /** + * Save a image URL to the registered account. + * + * @param string $url + * @param int $rating [Optional] + * @return string|boolean + * @throws Kohana_Gravatar_Xmlrpc_Exception + */ + public function save_url($url, $rating = NULL) + { + // If the URL supplied is not valid + if ( ! Validate::url($url)) + { + // Throw an exception + throw new Kohana_Gravatar_Xmlrpc_Exception(__METHOD__.' invalid URL supplied : :url', array(':url' => $url)); + } + + // If no rating has been applied, use general + if ($rating === NULL) + { + $rating = Gravatar_Xmlrpc::G; + } + + // Save the image to Gravatar + return $this->_xmlrpc_request('grav.saveData', array('url' => $url, 'rating' => $rating)); + } + + /** + * Assign a user image on Gravatar to the addresses + * supplied. + * + * @param string user_image + * @param array addresses + * @return array + */ + public function use_user_image($user_image, array $addresses) + { + // Set the userimage to all supplied addresses + return $this->_xmlrpc_request('grav.useUserimage', array('userImage' => $user_image, 'addresses' => $addresses)); + } + + /** + * Remove the userimage associated with one or more email addresses + * + * @param array addresses + * @return boolean + */ + public function remove_image(array $addresses) + { + // Remove the current image from the supplied addresses + return $this->_xmlrpc_request('grav.removeImage', array('addresses' => $addresses)); + } + + /** + * Remove a user image from the account and any email addresses with which it is associated + * + * @param string user_image + * @return boolean + */ + public function delete_user_image($user_image) + { + // Delete an image from the account + return $this->_xmlrpc_request('grav.deleteUserimage', array('userimage' => $user_image)); + } + + /** + * Processes an XML-RPC response based on the method and parameters passed + * to it. This method uses PHP streams over cURL, which makes it available + * to the vast majority of systems. + * + * @param string method + * @param array parameters + * @return mixed + * @throws Kohana_Gravatar_Xmlrpc_Exception + */ + protected function _xmlrpc_request($method, array $parameters = array()) + { + // Create the endpoint + $endpoint = $this->_prepare_service_endpoint(); + + // Apply the Gravatar user password to the parameters + $parameters['password'] = $this->_config['password']; + + // Create the XML-RPC request + $xml_payload = xmlrpc_encode_request($method, $parameters); + + // Create a context stream, enforcing a POST request with correct header + $context = stream_context_create(array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-Type: text/xml', + 'content' => $xml_payload + ) + )); + + try + { + // Process the XML-RPC request and decode the response + $xmlrpc_response = xmlrpc_decode(file_get_contents($endpoint, FALSE, $context)); + + // If there was an error + if ($xmlrpc_response and xmlrpc_is_fault($xmlrpc_response)) + { + // Throw an exception + throw new Kohana_Gravatar_Xmlrpc_Exception($xmlrpc_response['faultString'], NULL, $xmlrpc_response['faultCode']); + } + else + { + // return the response + return $xmlrpc_response; + } + + // Shouldn't get this far + throw new Kohana_Gravatar_Xmlrpc_Exception(__METHOD__.' something went wrong, xmlrpc_response was empty'); + } + // Catch all unexpected exceptions + catch (Exception $e) + { + throw new Kohana_Gravatar_Xmlrpc_Exception($e->getMessage(), NULL, $e->getCode()); + } + } + + /** + * Execute the Xmlrpc request and return + * the result + * + * @return mixed + * @throws Kohana_Gravatar_Xmlrpc_Exception + */ + protected function _prepare_service_endpoint() + { + if ($this->_config['email'] === NULL) + { + throw new Kohana_Gravatar_Xmlrpc_Exception('Username must be supplied to perform Gravatar API requests!'); + } + + // Generate full uri with user id + return $this->_config['service'].'?user='.md5($this->_config['email']); + } +} \ No newline at end of file diff --git a/classes/kohana/gravatar/xmlrpc/exception.php b/classes/kohana/gravatar/xmlrpc/exception.php new file mode 100644 index 0000000..19a8053 --- /dev/null +++ b/classes/kohana/gravatar/xmlrpc/exception.php @@ -0,0 +1,10 @@ +<?php defined('SYSPATH') or die('No direct script access.'); +/** + * @package Kohana + * @category Gravatar + * @version 3.1.0 + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Gravatar_Xmlrpc_Exception extends Kohana_Gravatar_Exception {} diff --git a/views/gravatar/image.php b/views/gravatar/image.php index 9edf349..d6a32bc 100644 --- a/views/gravatar/image.php +++ b/views/gravatar/image.php @@ -1 +1 @@ -<?= html::image($src, $alt); ?> \ No newline at end of file +<?php echo html::image($src, $alt); ?> \ No newline at end of file
samsoir/kohana-gravatar
2467933d44ffb7f9313a63d4dba400b0c050b0a6
Fixed some typos
diff --git a/classes/gravatar.php b/classes/gravatar.php index 0fc5c59..901e90c 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -1,282 +1,282 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [Gravatar's](http://en.gravatar.com) are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * @package Gravatar for Kohana PHP 3 * @author The Kohana Team * @copyright Copyright (c) 2009-2010 Kohana * @version 3.1.0 * @license Kohana License http://kohanaframework.org/license */ class Gravatar { const GRAVATAR_G = 'G'; const GRAVATAR_PG = 'PG'; const GRAVATAR_R = 'R'; const GRAVATAR_X = 'X'; /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) { self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); } // Return a the instance return self::$_instances[$email][$config_checksum]; } /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array */ public $attributes = array(); /** * The email address of the user * * @var string */ public $email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address $this->email = $email; if (empty($config)) { $this->_config = Kohana::config('gravatar.default'); } elseif (is_array($config)) { // Setup the configuration $config += Kohana::config('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { if ($config = Kohana::config('gravatar.'.$config) === NULL) { throw new Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); } $this->_config = $config + Kohana::config('gravatar.default'); } } /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self */ public function size($size = NULL) { if ($size === NULL) { return $this->_config['size']; } else { $this->_config['size'] = (int) $size; return $this; } } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self */ public function rating($rating = NULL) { $rating = strtoupper($rating); if ($rating === NULL) { return $this->_config['rating']; } else { if (in_array($rating, array(Gravatar::GRAVATAR_G, Gravatar::GRAVATAR_PG, Gravatar::GRAVATAR_R, Gravatar::GRAVATAR_X))) { $this->_config['rating'] = $rating; } else { throw new Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); } } return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self */ public function default_image($url = NULL) { if ($url === NULL) { return $this->_config['default']; } else { if (validate::url($url)) { $this->_config['default'] = $url; } else { throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); } } return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public * @author Sam Clark */ public function render($view = FALSE, $email = NULL) { if ($email !== NULL) { $this->email = $email; } $data = array('attr' => array(), 'src' => $this->_generate_url()); - if ($this->_attributes) + if ($this->attributes) { - $data['attr'] += $this->_attributes; + $data['attr'] += $this->attributes; } $data['attr']['alt'] = $this->_process_alt(); if ( ! $view) { return new View($this->_config['view'], $data); } else { return new View($view, $data); } } /** * Process the alt attribute output * * @return string * @access protected * @author Sam Clark */ protected function _process_alt() { $keys = array ( - '{$email}' => $this->_email, + '{$email}' => $this->email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) { $alt = strtr($this->_config['alt'], $keys); } else { $alt = FALSE; } return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected * @author Sam Clark */ protected function _generate_url() { $string = $this->_config['service']. - '?gravatar_id='.md5($this->_email). + '?gravatar_id='.md5($this->email). '&s='.$this->_config['size']. '&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) { $string .= '&d='.$this->_config['default']; } return $string; } } \ No newline at end of file
samsoir/kohana-gravatar
aec7be041b9bcc3c8c3622f5d8c9b4bd377652df
Fixed issue with non-existent issue
diff --git a/classes/gravatar.php b/classes/gravatar.php index 9d1d66f..0fc5c59 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -1,282 +1,282 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [Gravatar's](http://en.gravatar.com) are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * @package Gravatar for Kohana PHP 3 * @author The Kohana Team * @copyright Copyright (c) 2009-2010 Kohana * @version 3.1.0 * @license Kohana License http://kohanaframework.org/license */ class Gravatar { const GRAVATAR_G = 'G'; const GRAVATAR_PG = 'PG'; const GRAVATAR_R = 'R'; const GRAVATAR_X = 'X'; /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) { self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); } // Return a the instance return self::$_instances[$email][$config_checksum]; } /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array */ public $attributes = array(); /** * The email address of the user * * @var string */ public $email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address - $this->email($email); + $this->email = $email; if (empty($config)) { $this->_config = Kohana::config('gravatar.default'); } elseif (is_array($config)) { // Setup the configuration $config += Kohana::config('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { if ($config = Kohana::config('gravatar.'.$config) === NULL) { throw new Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); } $this->_config = $config + Kohana::config('gravatar.default'); } } /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self */ public function size($size = NULL) { if ($size === NULL) { return $this->_config['size']; } else { $this->_config['size'] = (int) $size; return $this; } } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self */ public function rating($rating = NULL) { $rating = strtoupper($rating); if ($rating === NULL) { return $this->_config['rating']; } else { if (in_array($rating, array(Gravatar::GRAVATAR_G, Gravatar::GRAVATAR_PG, Gravatar::GRAVATAR_R, Gravatar::GRAVATAR_X))) { $this->_config['rating'] = $rating; } else { throw new Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); } } return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self */ public function default_image($url = NULL) { if ($url === NULL) { return $this->_config['default']; } else { if (validate::url($url)) { $this->_config['default'] = $url; } else { throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); } } return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public * @author Sam Clark */ public function render($view = FALSE, $email = NULL) { if ($email !== NULL) { $this->email = $email; } $data = array('attr' => array(), 'src' => $this->_generate_url()); if ($this->_attributes) { $data['attr'] += $this->_attributes; } $data['attr']['alt'] = $this->_process_alt(); if ( ! $view) { return new View($this->_config['view'], $data); } else { return new View($view, $data); } } /** * Process the alt attribute output * * @return string * @access protected * @author Sam Clark */ protected function _process_alt() { $keys = array ( '{$email}' => $this->_email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) { $alt = strtr($this->_config['alt'], $keys); } else { $alt = FALSE; } return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected * @author Sam Clark */ protected function _generate_url() { $string = $this->_config['service']. '?gravatar_id='.md5($this->_email). '&s='.$this->_config['size']. '&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) { $string .= '&d='.$this->_config['default']; } return $string; } } \ No newline at end of file
samsoir/kohana-gravatar
268117e451796fec3480519fd456f1f0b5baa973
Fixed an issue where the Exception did not have the correct parameters passed to it
diff --git a/classes/gravatar/xmlrpc.php b/classes/gravatar/xmlrpc.php index f82156f..6139d93 100644 --- a/classes/gravatar/xmlrpc.php +++ b/classes/gravatar/xmlrpc.php @@ -1,304 +1,304 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar XMLRPC API for Kohana PHP 3 * @requires PHP-SOAP * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ */ class Gravatar_Xmlrpc { /** * Gravatar Ratings constants */ const G = 0; const PG = 1; const R = 2; const X = 3; /** * Create an instance of the Gravatar XMLRPC API client * * @param array $config * @return Gravatar_Xmlrpc * @access public */ public static function factory($config = array()) { return new Gravatar_Xmlrpc($config); } /** * @var array */ protected $_config; /** * Constructor * * @param array $config */ public function __construct($config) { // Check for soap if ( ! extension_loaded('XMLRPC')) { throw new Gravatar_Xmlrpc_Exception('XML-RPC extension must be loaded to use this class!'); } // Configure this library $config += Kohana::config('gravatar.xmlrpc'); $this->_config = $config; } /** * Set or get the password * * @param string $password * @return mixed */ public function password($password = NULL) { // If there is no API key supplied if ($password === NULL) { return $this->_config['password']; } // Else set the API key $this->_config['password'] = (string) $password; // Return this return $this; } /** * Set or get the email address in question * * @param string $email [Optional] * @return mixed */ public function email($email = NULL) { // If no argument, return the email address if ($email === NULL) { return $this->_config['email']; } // Set the email address $this->_config['email']; // Return this return $this; } /** * Checks that a hash exists * * @param array $hashes * @return array */ public function exists(array $hashes) { return $this->_xmlrpc_request('grav.exists', array('hashes' => $hashes)); } /** * Returns an array of email addresses * registered to the account API key * * @return array */ public function addresses() { return $this->_xmlrpc_request('grav.addresses'); } /** * Returns an array containing images * registered to this user - and their * respective rating * * @return array */ public function user_images() { return $this->_xmlrpc_request('grav.userimages'); } /** * Save an image to the registered account. * Images must be transferred in raw base64 * encoded format. * * @param string $image * @param int $rating [Optional] * @return string|boolean */ public function save_data($image, $rating = NULL) { // Load the image if ( ! $resource = file_get_contents($image)) { throw new Gravatar_Xmlrpc_Exception(__METHOD__.' unable to open image : :file', array(':file' => $image)); } // If no rating has been applied, use general if ($rating === NULL) { $rating = Gravatar_Xmlrpc::G; } // Encode the image resource $encoded_image = base64_encode($resource); // Save the image to Gravatar return $this->_xmlrpc_request('grav.saveData', array('data' => $encoded_image, 'rating' => $rating)); } /** * Save a image URL to the registered account. * * @param string $url * @param int $rating [Optional] * @return string|boolean */ public function save_url($url, $rating = NULL) { // If the URL supplied is not valid if ( ! Validate::url($url)) { // Throw an exception throw new Gravatar_Xmlrpc_Exception(__METHOD__.' invalid URL supplied : :url', array(':url' => $url)); } // If no rating has been applied, use general if ($rating === NULL) { $rating = Gravatar_Xmlrpc::G; } // Save the image to Gravatar return $this->_xmlrpc_request('grav.saveData', array('url' => $url, 'rating' => $rating)); } /** * Assign a user image on Gravatar to the addresses * supplied. * * @param string user_image * @param array addresses * @return array */ public function use_user_image($user_image, array $addresses) { // Set the userimage to all supplied addresses return $this->_xmlrpc_request('grav.useUserimage', array('userImage' => $user_image, 'addresses' => $addresses)); } /** * Remove the userimage associated with one or more email addresses * * @param array addresses * @return boolean */ public function remove_image(array $addresses) { // Remove the current image from the supplied addresses return $this->_xmlrpc_request('grav.removeImage', array('addresses' => $addresses)); } /** * Remove a user image from the account and any email addresses with which it is associated * * @param string user_image * @return boolean */ public function delete_user_image($user_image) { // Delete an image from the account return $this->_xmlrpc_request('grav.deleteUserimage', array('userimage' => $user_image)); } /** * Processes an XML-RPC response based on the method and parameters passed * to it. This method uses PHP streams over cURL, which makes it available * to the vast majority of systems. * * @param string method * @param array parameters * @return mixed */ protected function _xmlrpc_request($method, array $parameters = array()) { // Create the endpoint $endpoint = $this->_prepare_service_endpoint(); // Apply the Gravatar user password to the parameters $parameters['password'] = $this->_config['password']; // Create the XML-RPC request $xml_payload = xmlrpc_encode_request($method, $parameters); // Create a context stream, enforcing a POST request with correct header $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => 'Content-Type: text/xml', 'content' => $xml_payload ) )); try { // Process the XML-RPC request and decode the response $xmlrpc_response = xmlrpc_decode(file_get_contents($endpoint, FALSE, $context)); // If there was an error if ($xmlrpc_response and xmlrpc_is_fault($xmlrpc_response)) { // Throw an exception throw new Gravatar_Xmlrpc_Exception($xmlrpc_response['faultString'], NULL, $xmlrpc_response['faultCode']); } else { // return the response return $xmlrpc_response; } // Shouldn't get this far throw new Gravatar_Xmlrpc_Exception(__METHOD__.' something went wrong, xmlrpc_response was empty'); } // Catch all unexpected exceptions catch (Exception $e) { - throw new Gravatar_Xmlrpc_Exception($e->getMessage(), 0); + throw new Gravatar_Xmlrpc_Exception($e->getMessage(), NULL, $e->getCode()); } } /** * Execute the Xmlrpc request and return * the result * * @return mixed */ protected function _prepare_service_endpoint() { if ($this->_config['email'] === NULL) { throw new Gravatar_Xmlrpc_Exception('Username must be supplied to perform Gravatar API requests!'); } // Generate full uri with user id return $this->_config['service'].'?user='.md5($this->_config['email']); } } \ No newline at end of file
samsoir/kohana-gravatar
75e9c3a59dcaa0bb6e57580a7ef01aadacb3999b
Refactored the Gravatar class to bring it inline with Kohana 3 coding standards
diff --git a/classes/gravatar.php b/classes/gravatar.php index e4d884c..9d1d66f 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -1,335 +1,282 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** - * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. + * [Gravatar's](http://en.gravatar.com) are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. - * - * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar for Kohana PHP 3 - * @author Sam C. De Freyssinet - * @copyright (c) 2009 De Freyssinet - * @version 3.0.0 - * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ + * @author The Kohana Team + * @copyright Copyright (c) 2009-2010 Kohana + * @version 3.1.0 + * @license Kohana License http://kohanaframework.org/license */ class Gravatar { + const GRAVATAR_G = 'G'; + const GRAVATAR_PG = 'PG'; + const GRAVATAR_R = 'R'; + const GRAVATAR_X = 'X'; + /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ - public static function & instance($email, $config = NULL) + public static function instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) + { self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); + } // Return a the instance return self::$_instances[$email][$config_checksum]; } - /** - * Factory method - * - * @param string email the Gravatar to fetch for email address - * @param string config the name of the configuration grouping - * @param array config array of key value configuration pairs - * @return Gravatar - * @access public - * @static - */ - public static function factory($email, $config = NULL) - { - return new Gravatar($email, $config); - } - - /** - * Gravatar Ratings constants - */ - const GRAVATAR_G = 'G'; - const GRAVATAR_PG = 'PG'; - const GRAVATAR_R = 'R'; - const GRAVATAR_X = 'X'; - /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array - * @access protected */ - protected $_attributes = array(); + public $attributes = array(); /** * The email address of the user * * @var string - * @access protected */ - protected $_email; + public $email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address $this->email($email); if (empty($config)) + { $this->_config = Kohana::config('gravatar.default'); + } elseif (is_array($config)) { // Setup the configuration $config += Kohana::config('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { if ($config = Kohana::config('gravatar.'.$config) === NULL) + { throw new Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); + } $this->_config = $config + Kohana::config('gravatar.default'); } } - /** - * __get() magic method for accessing email value - * - * @param mixed key the key to get - * @return mixed the returned value - * @access public - */ - public function __get($key) - { - if ($key === 'email') - { - $key = '_'.$key; - return $this->$key; - } - elseif ($this->config[$key] !== NULL) - return $this->_config[$key]; - elseif ($this->attributes[$key] !== NULL) - return $this->_attributes[$key]; - else - return NULL; - } - - /** - * __set() magic method for setting object properties - * If $var is a method then this will call it, else it will - * set the attribute $key = $value - * - * @param string $key - * @param string $value - * @return void - * @author Sam Clark - */ - public function __set($key, $value) - { - if ($key === 'email') - { - $key = '_'.$key; - $this->$key; - } - else - $result = $this->add_attribute($key, $value); - - } - /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } - /** - * Accessor method for setting email address - * - * @param string email the valid email address of Gravatar user - * @return self - * @access public - * @author Sam Clark - */ - public function email($email) - { - if (validate::email($email)) - $this->_email = strtolower($email); - else - throw new Gravatar_Exception('The email address : :email is incorrectly formatted', array(':email' => $email)); - - return $this; - } - /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self - * @access public - * @author Sam Clark */ - public function size($size) + public function size($size = NULL) { - if (ctype_digit((string) $size)) - $this->_config['size'] = (int) $size; + if ($size === NULL) + { + return $this->_config['size']; + } else - throw new Gravatar_Exception('The image size must be greater than zero'); - - return $this; + { + $this->_config['size'] = (int) $size; + return $this; + } } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self - * @access public - * @author Sam Clark */ - public function rating($rating) + public function rating($rating = NULL) { - if (in_array(strtoupper($rating), array('G', 'PG', 'R', 'X'))) - $this->_config['rating'] = strtoupper($rating); + $rating = strtoupper($rating); + + if ($rating === NULL) + { + return $this->_config['rating']; + } else - throw new Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); + { + if (in_array($rating, array(Gravatar::GRAVATAR_G, Gravatar::GRAVATAR_PG, Gravatar::GRAVATAR_R, Gravatar::GRAVATAR_X))) + { + $this->_config['rating'] = $rating; + } + else + { + throw new Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); + } + } return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self - * @access public - * @author Sam Clark */ - public function default_image($url) + public function default_image($url = NULL) { - if (validate::url($url)) - $this->_config['default'] = $url; + if ($url === NULL) + { + return $this->_config['default']; + } else - throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); - - return $this; - } - - /** - * Allows addition of custom HTML attributes such as 'id' or 'class'. - * - * @param string key the attribute key - * @param string value the attribute value - * @return self - * @access public - * @author Sam Clark - */ - public function add_attribute($key, $value) - { - $this->_attributes[$key] = $value; + { + if (validate::url($url)) + { + $this->_config['default'] = $url; + } + else + { + throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); + } + } return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public * @author Sam Clark */ public function render($view = FALSE, $email = NULL) { - if (isset($email)) - $this->email($email); + if ($email !== NULL) + { + $this->email = $email; + } $data = array('attr' => array(), 'src' => $this->_generate_url()); if ($this->_attributes) + { $data['attr'] += $this->_attributes; + } $data['attr']['alt'] = $this->_process_alt(); - return (string) $view ? new View($view, $data) : new View($this->_config['view'], $data);; + if ( ! $view) + { + return new View($this->_config['view'], $data); + } + else + { + return new View($view, $data); + } } /** * Process the alt attribute output * * @return string * @access protected * @author Sam Clark */ protected function _process_alt() { $keys = array ( '{$email}' => $this->_email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) + { $alt = strtr($this->_config['alt'], $keys); + } else + { $alt = FALSE; + } return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected * @author Sam Clark */ protected function _generate_url() { - $string = $this->_config['service'].'?gravatar_id='.md5($this->_email).'&s='.$this->_config['size'].'&r='.$this->_config['rating']; + $string = $this->_config['service']. + '?gravatar_id='.md5($this->_email). + '&s='.$this->_config['size']. + '&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) + { $string .= '&d='.$this->_config['default']; + } return $string; } } \ No newline at end of file
samsoir/kohana-gravatar
9520edc0f52e275330a1da6e7b3c9b5e4a32c54a
Fixed a few minor issues with XMLRPC url generation
diff --git a/classes/gravatar/xmlrpc.php b/classes/gravatar/xmlrpc.php index 2f88ec5..f82156f 100644 --- a/classes/gravatar/xmlrpc.php +++ b/classes/gravatar/xmlrpc.php @@ -1,304 +1,304 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar XMLRPC API for Kohana PHP 3 * @requires PHP-SOAP * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ */ class Gravatar_Xmlrpc { /** * Gravatar Ratings constants */ const G = 0; const PG = 1; const R = 2; const X = 3; /** * Create an instance of the Gravatar XMLRPC API client * * @param array $config * @return Gravatar_Xmlrpc * @access public */ public static function factory($config = array()) { return new Gravatar_Xmlrpc($config); } /** * @var array */ protected $_config; /** * Constructor * * @param array $config */ public function __construct($config) { // Check for soap if ( ! extension_loaded('XMLRPC')) { throw new Gravatar_Xmlrpc_Exception('XML-RPC extension must be loaded to use this class!'); } // Configure this library $config += Kohana::config('gravatar.xmlrpc'); $this->_config = $config; } /** * Set or get the password * * @param string $password * @return mixed */ public function password($password = NULL) { // If there is no API key supplied if ($password === NULL) { return $this->_config['password']; } // Else set the API key $this->_config['password'] = (string) $password; // Return this return $this; } /** * Set or get the email address in question * * @param string $email [Optional] * @return mixed */ public function email($email = NULL) { // If no argument, return the email address if ($email === NULL) { return $this->_config['email']; } // Set the email address $this->_config['email']; // Return this return $this; } /** * Checks that a hash exists * * @param array $hashes * @return array */ public function exists(array $hashes) { return $this->_xmlrpc_request('grav.exists', array('hashes' => $hashes)); } /** * Returns an array of email addresses * registered to the account API key * * @return array */ public function addresses() { return $this->_xmlrpc_request('grav.addresses'); } /** * Returns an array containing images * registered to this user - and their * respective rating * * @return array */ public function user_images() { return $this->_xmlrpc_request('grav.userimages'); } /** * Save an image to the registered account. * Images must be transferred in raw base64 * encoded format. * * @param string $image * @param int $rating [Optional] * @return string|boolean */ public function save_data($image, $rating = NULL) { // Load the image if ( ! $resource = file_get_contents($image)) { throw new Gravatar_Xmlrpc_Exception(__METHOD__.' unable to open image : :file', array(':file' => $image)); } // If no rating has been applied, use general if ($rating === NULL) { $rating = Gravatar_Xmlrpc::G; } // Encode the image resource $encoded_image = base64_encode($resource); // Save the image to Gravatar return $this->_xmlrpc_request('grav.saveData', array('data' => $encoded_image, 'rating' => $rating)); } /** * Save a image URL to the registered account. * * @param string $url * @param int $rating [Optional] * @return string|boolean */ public function save_url($url, $rating = NULL) { // If the URL supplied is not valid if ( ! Validate::url($url)) { // Throw an exception throw new Gravatar_Xmlrpc_Exception(__METHOD__.' invalid URL supplied : :url', array(':url' => $url)); } // If no rating has been applied, use general if ($rating === NULL) { $rating = Gravatar_Xmlrpc::G; } // Save the image to Gravatar return $this->_xmlrpc_request('grav.saveData', array('url' => $url, 'rating' => $rating)); } /** * Assign a user image on Gravatar to the addresses * supplied. * * @param string user_image * @param array addresses * @return array */ public function use_user_image($user_image, array $addresses) { // Set the userimage to all supplied addresses return $this->_xmlrpc_request('grav.useUserimage', array('userImage' => $user_image, 'addresses' => $addresses)); } /** * Remove the userimage associated with one or more email addresses * * @param array addresses * @return boolean */ public function remove_image(array $addresses) { // Remove the current image from the supplied addresses return $this->_xmlrpc_request('grav.removeImage', array('addresses' => $addresses)); } /** * Remove a user image from the account and any email addresses with which it is associated * * @param string user_image * @return boolean */ public function delete_user_image($user_image) { // Delete an image from the account return $this->_xmlrpc_request('grav.deleteUserimage', array('userimage' => $user_image)); } /** * Processes an XML-RPC response based on the method and parameters passed * to it. This method uses PHP streams over cURL, which makes it available * to the vast majority of systems. * * @param string method * @param array parameters * @return mixed */ protected function _xmlrpc_request($method, array $parameters = array()) { // Create the endpoint $endpoint = $this->_prepare_service_endpoint(); // Apply the Gravatar user password to the parameters $parameters['password'] = $this->_config['password']; // Create the XML-RPC request $xml_payload = xmlrpc_encode_request($method, $parameters); // Create a context stream, enforcing a POST request with correct header $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => 'Content-Type: text/xml', 'content' => $xml_payload ) )); try { // Process the XML-RPC request and decode the response $xmlrpc_response = xmlrpc_decode(file_get_contents($endpoint, FALSE, $context)); // If there was an error if ($xmlrpc_response and xmlrpc_is_fault($xmlrpc_response)) { // Throw an exception throw new Gravatar_Xmlrpc_Exception($xmlrpc_response['faultString'], NULL, $xmlrpc_response['faultCode']); } else { // return the response return $xmlrpc_response; } // Shouldn't get this far throw new Gravatar_Xmlrpc_Exception(__METHOD__.' something went wrong, xmlrpc_response was empty'); } // Catch all unexpected exceptions catch (Exception $e) { throw new Gravatar_Xmlrpc_Exception($e->getMessage(), 0); } } /** * Execute the Xmlrpc request and return * the result * * @return mixed */ protected function _prepare_service_endpoint() { - if ($user === NULL or $password === NULL) + if ($this->_config['email'] === NULL) { - throw new Gravatar_Xmlrpc_Exception('Username and Password must be supplied to perform Gravatar API requests!'); + throw new Gravatar_Xmlrpc_Exception('Username must be supplied to perform Gravatar API requests!'); } // Generate full uri with user id return $this->_config['service'].'?user='.md5($this->_config['email']); } } \ No newline at end of file
samsoir/kohana-gravatar
710c4c6804d7cf3e359b230426fc53b93f4db7c1
Revoked the singleton pattern. Multiple instances are now allowed
diff --git a/classes/gravatar/xmlrpc.php b/classes/gravatar/xmlrpc.php index 64d83f5..2f88ec5 100644 --- a/classes/gravatar/xmlrpc.php +++ b/classes/gravatar/xmlrpc.php @@ -1,308 +1,304 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar XMLRPC API for Kohana PHP 3 * @requires PHP-SOAP * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ */ class Gravatar_Xmlrpc { /** * Gravatar Ratings constants */ const G = 0; const PG = 1; const R = 2; const X = 3; /** * Create an instance of the Gravatar XMLRPC API client * * @param array $config * @return Gravatar_Xmlrpc * @access public */ - public static function instance($config = array()) + public static function factory($config = array()) { - static $instance; - - empty($instance) and $instance = new Gravatar_Xmlrpc($config); - - return $instance; + return new Gravatar_Xmlrpc($config); } /** * @var array */ protected $_config; /** - * Constructor, maintains the singleton or factory pattern + * Constructor * * @param array $config */ - protected function __construct($config) + public function __construct($config) { // Check for soap if ( ! extension_loaded('XMLRPC')) { throw new Gravatar_Xmlrpc_Exception('XML-RPC extension must be loaded to use this class!'); } // Configure this library $config += Kohana::config('gravatar.xmlrpc'); $this->_config = $config; } /** * Set or get the password * * @param string $password * @return mixed */ public function password($password = NULL) { // If there is no API key supplied if ($password === NULL) { return $this->_config['password']; } // Else set the API key $this->_config['password'] = (string) $password; // Return this return $this; } /** * Set or get the email address in question * * @param string $email [Optional] * @return mixed */ public function email($email = NULL) { // If no argument, return the email address if ($email === NULL) { return $this->_config['email']; } // Set the email address $this->_config['email']; // Return this return $this; } /** * Checks that a hash exists * * @param array $hashes * @return array */ public function exists(array $hashes) { return $this->_xmlrpc_request('grav.exists', array('hashes' => $hashes)); } /** * Returns an array of email addresses * registered to the account API key * * @return array */ public function addresses() { return $this->_xmlrpc_request('grav.addresses'); } /** * Returns an array containing images * registered to this user - and their * respective rating * * @return array */ public function user_images() { return $this->_xmlrpc_request('grav.userimages'); } /** * Save an image to the registered account. * Images must be transferred in raw base64 * encoded format. * * @param string $image * @param int $rating [Optional] * @return string|boolean */ public function save_data($image, $rating = NULL) { // Load the image if ( ! $resource = file_get_contents($image)) { throw new Gravatar_Xmlrpc_Exception(__METHOD__.' unable to open image : :file', array(':file' => $image)); } // If no rating has been applied, use general if ($rating === NULL) { $rating = Gravatar_Xmlrpc::G; } // Encode the image resource $encoded_image = base64_encode($resource); // Save the image to Gravatar return $this->_xmlrpc_request('grav.saveData', array('data' => $encoded_image, 'rating' => $rating)); } /** * Save a image URL to the registered account. * * @param string $url * @param int $rating [Optional] * @return string|boolean */ public function save_url($url, $rating = NULL) { // If the URL supplied is not valid if ( ! Validate::url($url)) { // Throw an exception throw new Gravatar_Xmlrpc_Exception(__METHOD__.' invalid URL supplied : :url', array(':url' => $url)); } // If no rating has been applied, use general if ($rating === NULL) { $rating = Gravatar_Xmlrpc::G; } // Save the image to Gravatar return $this->_xmlrpc_request('grav.saveData', array('url' => $url, 'rating' => $rating)); } /** * Assign a user image on Gravatar to the addresses * supplied. * * @param string user_image * @param array addresses * @return array */ public function use_user_image($user_image, array $addresses) { // Set the userimage to all supplied addresses return $this->_xmlrpc_request('grav.useUserimage', array('userImage' => $user_image, 'addresses' => $addresses)); } /** * Remove the userimage associated with one or more email addresses * * @param array addresses * @return boolean */ public function remove_image(array $addresses) { // Remove the current image from the supplied addresses return $this->_xmlrpc_request('grav.removeImage', array('addresses' => $addresses)); } /** * Remove a user image from the account and any email addresses with which it is associated * * @param string user_image * @return boolean */ public function delete_user_image($user_image) { // Delete an image from the account return $this->_xmlrpc_request('grav.deleteUserimage', array('userimage' => $user_image)); } /** * Processes an XML-RPC response based on the method and parameters passed * to it. This method uses PHP streams over cURL, which makes it available * to the vast majority of systems. * * @param string method * @param array parameters * @return mixed */ protected function _xmlrpc_request($method, array $parameters = array()) { // Create the endpoint $endpoint = $this->_prepare_service_endpoint(); // Apply the Gravatar user password to the parameters $parameters['password'] = $this->_config['password']; // Create the XML-RPC request $xml_payload = xmlrpc_encode_request($method, $parameters); // Create a context stream, enforcing a POST request with correct header $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => 'Content-Type: text/xml', 'content' => $xml_payload ) )); try { // Process the XML-RPC request and decode the response $xmlrpc_response = xmlrpc_decode(file_get_contents($endpoint, FALSE, $context)); // If there was an error if ($xmlrpc_response and xmlrpc_is_fault($xmlrpc_response)) { // Throw an exception throw new Gravatar_Xmlrpc_Exception($xmlrpc_response['faultString'], NULL, $xmlrpc_response['faultCode']); } else { // return the response return $xmlrpc_response; } // Shouldn't get this far throw new Gravatar_Xmlrpc_Exception(__METHOD__.' something went wrong, xmlrpc_response was empty'); } // Catch all unexpected exceptions catch (Exception $e) { throw new Gravatar_Xmlrpc_Exception($e->getMessage(), 0); } } /** * Execute the Xmlrpc request and return * the result * * @return mixed */ protected function _prepare_service_endpoint() { if ($user === NULL or $password === NULL) { throw new Gravatar_Xmlrpc_Exception('Username and Password must be supplied to perform Gravatar API requests!'); } // Generate full uri with user id return $this->_config['service'].'?user='.md5($this->_config['email']); } } \ No newline at end of file
samsoir/kohana-gravatar
c4e894efcfdbac2e5e39932e803667519d0ee9b4
Implemented the Gravatar XMLRPC interface, providing full access to the gravatar API
diff --git a/classes/gravatar/exception/xmlrpc.php b/classes/gravatar/exception/xmlrpc.php deleted file mode 100644 index d11cb6d..0000000 --- a/classes/gravatar/exception/xmlrpc.php +++ /dev/null @@ -1,10 +0,0 @@ -<?php defined('SYSPATH') or die('No direct script access.'); - -class Gravatar_Exception_Xmlrpc extends Gravatar_Exception { - - public function __construct($message, $code = NULL) - { - parent::__construct($message, NULL, $code); - } - -} \ No newline at end of file diff --git a/classes/gravatar/xmlrpc.php b/classes/gravatar/xmlrpc.php index 86d4695..64d83f5 100644 --- a/classes/gravatar/xmlrpc.php +++ b/classes/gravatar/xmlrpc.php @@ -1,235 +1,308 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar XMLRPC API for Kohana PHP 3 * @requires PHP-SOAP * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ */ class Gravatar_Xmlrpc { + /** + * Gravatar Ratings constants + */ + const G = 0; + const PG = 1; + const R = 2; + const X = 3; + + /** * Create an instance of the Gravatar XMLRPC API client * * @param array $config - * @return self + * @return Gravatar_Xmlrpc * @access public - * @static */ public static function instance($config = array()) { static $instance; empty($instance) and $instance = new Gravatar_Xmlrpc($config); return $instance; } /** - * Factory method for creating a new Xmlrpc object - * - * @param array $config - * @return self - * @access public - * @static - */ - public static function factory($config = array()) - { - return new Gravatar_Xmlrpc($config); - } - - /** - * Configuration for this client - * * @var array */ protected $_config; - /** - * Xml Writing Driver - * - * @var mixed - */ - protected $_xmlWriter; - - /** - * SOAP Client - * - * @var SoapClient - */ - protected $_soapClient; - /** * Constructor, maintains the singleton or factory pattern * * @param array $config - * @access protected */ protected function __construct($config) { // Check for soap - if ( ! extension_loaded('Soap')) - throw new Gravatar_Exception('Soap extension must be loaded to use this class!'); + if ( ! extension_loaded('XMLRPC')) + { + throw new Gravatar_Xmlrpc_Exception('XML-RPC extension must be loaded to use this class!'); + } // Configure this library $config += Kohana::config('gravatar.xmlrpc'); $this->_config = $config; - - // Setup SOAP Client - $this->_soapClient = new SoapClient(null, array - ( - 'location' => request::instance()->uri, - 'uri' => $this->_config['service'].$this->_config['email'], - )); } /** - * Set or get the api_key + * Set or get the password * - * @param string $api_key - * @return string|self - * @access public + * @param string $password + * @return mixed */ - public function api_key($api_key = NULL) + public function password($password = NULL) { // If there is no API key supplied - if ($api_key === NULL) - return $this->_config['api_key']; + if ($password === NULL) + { + return $this->_config['password']; + } // Else set the API key - $this->_config['api_key'] = (string) $api_key; + $this->_config['password'] = (string) $password; // Return this return $this; } /** * Set or get the email address in question * * @param string $email [Optional] - * @return string|self - * @access public + * @return mixed */ public function email($email = NULL) { // If no argument, return the email address if ($email === NULL) + { return $this->_config['email']; + } // Set the email address $this->_config['email']; // Return this return $this; } /** * Checks that a hash exists * * @param array $hashes * @return array - * @access public */ - public function check_hash($hashes) + public function exists(array $hashes) { - + return $this->_xmlrpc_request('grav.exists', array('hashes' => $hashes)); } /** * Returns an array of email addresses * registered to the account API key * * @return array - * @access public */ public function addresses() { - + return $this->_xmlrpc_request('grav.addresses'); } /** * Returns an array containing images * registered to this user - and their * respective rating * * @return array - * @access public */ public function user_images() { - + return $this->_xmlrpc_request('grav.userimages'); } /** * Save an image to the registered account. * Images must be transferred in raw base64 * encoded format. * * @param string $image * @param int $rating [Optional] * @return string|boolean - * @access public */ - public function save_data($image, $rating = 0) + public function save_data($image, $rating = NULL) { - + // Load the image + if ( ! $resource = file_get_contents($image)) + { + throw new Gravatar_Xmlrpc_Exception(__METHOD__.' unable to open image : :file', array(':file' => $image)); + } + + // If no rating has been applied, use general + if ($rating === NULL) + { + $rating = Gravatar_Xmlrpc::G; + } + + // Encode the image resource + $encoded_image = base64_encode($resource); + + // Save the image to Gravatar + return $this->_xmlrpc_request('grav.saveData', array('data' => $encoded_image, 'rating' => $rating)); } /** - * Save a URL to the registered account. + * Save a image URL to the registered account. * * @param string $url * @param int $rating [Optional] * @return string|boolean - * @access public */ - public function save_url($url, $rating = 0) + public function save_url($url, $rating = NULL) { - + // If the URL supplied is not valid + if ( ! Validate::url($url)) + { + // Throw an exception + throw new Gravatar_Xmlrpc_Exception(__METHOD__.' invalid URL supplied : :url', array(':url' => $url)); + } + + // If no rating has been applied, use general + if ($rating === NULL) + { + $rating = Gravatar_Xmlrpc::G; + } + + // Save the image to Gravatar + return $this->_xmlrpc_request('grav.saveData', array('url' => $url, 'rating' => $rating)); } /** * Assign a user image on Gravatar to the addresses * supplied. * - * @param string $user_image - * @param array $addresses + * @param string user_image + * @param array addresses * @return array - * @access public */ - public function use_image($user_image, $addresses) + public function use_user_image($user_image, array $addresses) { - + // Set the userimage to all supplied addresses + return $this->_xmlrpc_request('grav.useUserimage', array('userImage' => $user_image, 'addresses' => $addresses)); } /** - * Test function + * Remove the userimage associated with one or more email addresses * + * @param array addresses + * @return boolean + */ + public function remove_image(array $addresses) + { + // Remove the current image from the supplied addresses + return $this->_xmlrpc_request('grav.removeImage', array('addresses' => $addresses)); + } + + /** + * Remove a user image from the account and any email addresses with which it is associated + * + * @param string user_image + * @return boolean + */ + public function delete_user_image($user_image) + { + // Delete an image from the account + return $this->_xmlrpc_request('grav.deleteUserimage', array('userimage' => $user_image)); + } + + /** + * Processes an XML-RPC response based on the method and parameters passed + * to it. This method uses PHP streams over cURL, which makes it available + * to the vast majority of systems. + * + * @param string method + * @param array parameters * @return mixed - * @access public */ - public function test() + protected function _xmlrpc_request($method, array $parameters = array()) { - + // Create the endpoint + $endpoint = $this->_prepare_service_endpoint(); + + // Apply the Gravatar user password to the parameters + $parameters['password'] = $this->_config['password']; + + // Create the XML-RPC request + $xml_payload = xmlrpc_encode_request($method, $parameters); + + // Create a context stream, enforcing a POST request with correct header + $context = stream_context_create(array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-Type: text/xml', + 'content' => $xml_payload + ) + )); + + try + { + // Process the XML-RPC request and decode the response + $xmlrpc_response = xmlrpc_decode(file_get_contents($endpoint, FALSE, $context)); + + // If there was an error + if ($xmlrpc_response and xmlrpc_is_fault($xmlrpc_response)) + { + // Throw an exception + throw new Gravatar_Xmlrpc_Exception($xmlrpc_response['faultString'], NULL, $xmlrpc_response['faultCode']); + } + else + { + // return the response + return $xmlrpc_response; + } + + // Shouldn't get this far + throw new Gravatar_Xmlrpc_Exception(__METHOD__.' something went wrong, xmlrpc_response was empty'); + } + // Catch all unexpected exceptions + catch (Exception $e) + { + throw new Gravatar_Xmlrpc_Exception($e->getMessage(), 0); + } } /** * Execute the Xmlrpc request and return * the result * * @return mixed - * @access protected */ - protected function _exec() + protected function _prepare_service_endpoint() { - - + if ($user === NULL or $password === NULL) + { + throw new Gravatar_Xmlrpc_Exception('Username and Password must be supplied to perform Gravatar API requests!'); + } + + // Generate full uri with user id + return $this->_config['service'].'?user='.md5($this->_config['email']); } } \ No newline at end of file diff --git a/classes/gravatar/xmlrpc/exception.php b/classes/gravatar/xmlrpc/exception.php new file mode 100644 index 0000000..561a47c --- /dev/null +++ b/classes/gravatar/xmlrpc/exception.php @@ -0,0 +1,3 @@ +<?php defined('SYSPATH') or die('No direct script access.'); + +class Gravatar_Xmlrpc_Exception extends Gravatar_Exception {} diff --git a/config/gravatar.php b/config/gravatar.php index 53d22a5..d02075e 100644 --- a/config/gravatar.php +++ b/config/gravatar.php @@ -1,17 +1,17 @@ <?php defined('SYSPATH') or die('No direct script access.'); return array( 'default' => array( 'service' => 'http://www.gravatar.com/avatar.php', // The gravatar service URL 'default_image' => FALSE, // The default image if Gravatar is not found, FALSE uses Gravatar default 'size' => 100, // The size of the returned gravatar 'view' => 'gravatar/image', // The default view 'rating' => Gravatar::GRAVATAR_G, // The default rating 'alt' => FALSE, // Alternate image string, FALSE to omit, string to include ), 'xmlrpc' => array( - 'service' => 'https://secure.gravatar.com/xmlrpc?user=', - 'api_key' => '', - 'email' => '', + 'service' => 'https://secure.gravatar.com/xmlrpc', + 'email' => NULL, + 'password' => NULL, ), ); \ No newline at end of file
samsoir/kohana-gravatar
65a328fe69803e969eb6883c7f7b85e477344e51
Fixes all reported issues with Gravatar. Thanks to all reporters (biakaveron and frihani)
diff --git a/classes/gravatar.php b/classes/gravatar.php index d7fd802..e4d884c 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -1,335 +1,335 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar for Kohana PHP 3 * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ */ class Gravatar { /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function & instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); // Return a the instance return self::$_instances[$email][$config_checksum]; } /** * Factory method * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function factory($email, $config = NULL) { return new Gravatar($email, $config); } /** * Gravatar Ratings constants */ const GRAVATAR_G = 'G'; const GRAVATAR_PG = 'PG'; const GRAVATAR_R = 'R'; const GRAVATAR_X = 'X'; /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array * @access protected */ protected $_attributes = array(); /** * The email address of the user * * @var string * @access protected */ protected $_email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address $this->email($email); if (empty($config)) $this->_config = Kohana::config('gravatar.default'); elseif (is_array($config)) { // Setup the configuration $config += Kohana::config('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { if ($config = Kohana::config('gravatar.'.$config) === NULL) - throw new Gravatar_Exception(printf('Gravatar.__construct() , Invalid configuration group name : %s', $config)); + throw new Gravatar_Exception('Gravatar.__construct() , Invalid configuration group name : :config', array(':config' => $config)); - $this->_config = $config; + $this->_config = $config + Kohana::config('gravatar.default'); } } /** * __get() magic method for accessing email value * * @param mixed key the key to get * @return mixed the returned value * @access public */ public function __get($key) { if ($key === 'email') { $key = '_'.$key; return $this->$key; } elseif ($this->config[$key] !== NULL) return $this->_config[$key]; elseif ($this->attributes[$key] !== NULL) return $this->_attributes[$key]; else return NULL; } /** * __set() magic method for setting object properties * If $var is a method then this will call it, else it will * set the attribute $key = $value * * @param string $key * @param string $value * @return void * @author Sam Clark */ public function __set($key, $value) { if ($key === 'email') { $key = '_'.$key; $this->$key; } else $result = $this->add_attribute($key, $value); } /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } /** * Accessor method for setting email address * * @param string email the valid email address of Gravatar user * @return self * @access public * @author Sam Clark */ public function email($email) { if (validate::email($email)) $this->_email = strtolower($email); else - throw new Gravatar_Exception(printf('The email address %s is incorrectly formatted', $email)); + throw new Gravatar_Exception('The email address : :email is incorrectly formatted', array(':email' => $email)); return $this; } /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self * @access public * @author Sam Clark */ public function size($size) { if (ctype_digit((string) $size)) $this->_config['size'] = (int) $size; else throw new Gravatar_Exception('The image size must be greater than zero'); return $this; } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self * @access public * @author Sam Clark */ public function rating($rating) { if (in_array(strtoupper($rating), array('G', 'PG', 'R', 'X'))) $this->_config['rating'] = strtoupper($rating); else - throw new Gravatar_Exception(printf('The rating value %s is not valid. Please use G, PG, R or X. Also available through Class constants'), $rating); + throw new Gravatar_Exception('The rating value :rating is not valid. Please use G, PG, R or X. Also available through Class constants', array(':rating' => $rating)); return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self * @access public * @author Sam Clark */ public function default_image($url) { if (validate::url($url)) $this->_config['default'] = $url; else - throw new Gravatar(printf('The url %s is improperly formatted', $url)); + throw new Gravatar('The url : :url is improperly formatted', array(':url' => $url)); return $this; } /** * Allows addition of custom HTML attributes such as 'id' or 'class'. * * @param string key the attribute key * @param string value the attribute value * @return self * @access public * @author Sam Clark */ public function add_attribute($key, $value) { $this->_attributes[$key] = $value; return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public * @author Sam Clark */ public function render($view = FALSE, $email = NULL) { if (isset($email)) $this->email($email); - $data = array('src' => array('src' => $this->_generate_url())); + $data = array('attr' => array(), 'src' => $this->_generate_url()); if ($this->_attributes) - $data['src'] += $this->_attributes; + $data['attr'] += $this->_attributes; - $data['alt'] = $this->_process_alt(); + $data['attr']['alt'] = $this->_process_alt(); return (string) $view ? new View($view, $data) : new View($this->_config['view'], $data);; } /** * Process the alt attribute output * * @return string * @access protected * @author Sam Clark */ protected function _process_alt() { $keys = array ( '{$email}' => $this->_email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) $alt = strtr($this->_config['alt'], $keys); else $alt = FALSE; return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected * @author Sam Clark */ protected function _generate_url() { $string = $this->_config['service'].'?gravatar_id='.md5($this->_email).'&s='.$this->_config['size'].'&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) $string .= '&d='.$this->_config['default']; return $string; } } \ No newline at end of file diff --git a/views/gravatar/image.php b/views/gravatar/image.php new file mode 100644 index 0000000..9edf349 --- /dev/null +++ b/views/gravatar/image.php @@ -0,0 +1 @@ +<?= html::image($src, $alt); ?> \ No newline at end of file
samsoir/kohana-gravatar
29a9c9e14c0cb50eecec3e1605d06e77d597f2da
Refactored the XMLRPC class for gravatar. Now designed to use the naitive php soap client
diff --git a/classes/gravatar/xmlrpc.php b/classes/gravatar/xmlrpc.php index 14025a2..86d4695 100644 --- a/classes/gravatar/xmlrpc.php +++ b/classes/gravatar/xmlrpc.php @@ -1,199 +1,235 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar XMLRPC API for Kohana PHP 3 + * @requires PHP-SOAP * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ - * @abstract */ -abstract class Gravatar_Xmlrpc { +class Gravatar_Xmlrpc { /** * Create an instance of the Gravatar XMLRPC API client * * @param array $config * @return self * @access public * @static */ public static function instance($config = array()) { static $instance; empty($instance) and $instance = new Gravatar_Xmlrpc($config); return $instance; } /** * Factory method for creating a new Xmlrpc object * * @param array $config * @return self * @access public * @static */ public static function factory($config = array()) { return new Gravatar_Xmlrpc($config); } /** * Configuration for this client * * @var array */ protected $_config; + /** + * Xml Writing Driver + * + * @var mixed + */ + protected $_xmlWriter; + + /** + * SOAP Client + * + * @var SoapClient + */ + protected $_soapClient; + /** * Constructor, maintains the singleton or factory pattern * * @param array $config * @access protected */ protected function __construct($config) { + // Check for soap + if ( ! extension_loaded('Soap')) + throw new Gravatar_Exception('Soap extension must be loaded to use this class!'); + // Configure this library $config += Kohana::config('gravatar.xmlrpc'); $this->_config = $config; + + // Setup SOAP Client + $this->_soapClient = new SoapClient(null, array + ( + 'location' => request::instance()->uri, + 'uri' => $this->_config['service'].$this->_config['email'], + )); } /** * Set or get the api_key * * @param string $api_key * @return string|self * @access public */ public function api_key($api_key = NULL) { // If there is no API key supplied if ($api_key === NULL) return $this->_config['api_key']; // Else set the API key $this->_config['api_key'] = (string) $api_key; // Return this return $this; } /** * Set or get the email address in question * * @param string $email [Optional] * @return string|self * @access public */ public function email($email = NULL) { // If no argument, return the email address if ($email === NULL) return $this->_config['email']; // Set the email address $this->_config['email']; // Return this return $this; } /** * Checks that a hash exists * * @param array $hashes * @return array * @access public - * @abstract */ - abstract public function exists($hashes); + public function check_hash($hashes) + { + + } /** * Returns an array of email addresses * registered to the account API key * * @return array * @access public - * @abstract */ - abstract public function addresses(); + public function addresses() + { + + } /** * Returns an array containing images * registered to this user - and their * respective rating * * @return array * @access public - * @abstract */ - abstract public function userimages(); + public function user_images() + { + + } /** * Save an image to the registered account. * Images must be transferred in raw base64 * encoded format. * * @param string $image * @param int $rating [Optional] * @return string|boolean * @access public - * @abstract */ - abstract public function save_data($image, $rating = 0); + public function save_data($image, $rating = 0) + { + + } /** * Save a URL to the registered account. * * @param string $url * @param int $rating [Optional] * @return string|boolean * @access public - * @abstract */ - abstract public function save_url($url, $rating = 0); + public function save_url($url, $rating = 0) + { + + } /** * Assign a user image on Gravatar to the addresses * supplied. * * @param string $user_image * @param array $addresses * @return array * @access public - * @abstract */ - abstract public function use_userimage($user_image, $addresses); + public function use_image($user_image, $addresses) + { + + } /** * Test function * * @return mixed * @access public - * @abstract */ - abstract public function test(); + public function test() + { + + } /** * Execute the Xmlrpc request and return * the result * - * @param string $xml * @return mixed * @access protected */ - protected function _exec($xml) + protected function _exec() { - // Create the URL - $url = $this->_config['service'].md5($this->_config['email']); - - $result = Remote::get() + + } } \ No newline at end of file diff --git a/classes/gravatar/xmlrpc/dom.php b/classes/gravatar/xmlrpc/dom.php deleted file mode 100644 index 7b8b180..0000000 --- a/classes/gravatar/xmlrpc/dom.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php defined('SYSPATH') or die('No direct script access.'); - -class Gravatar_Xmlrpc_Dom extends Gravatar_Xmlrpc { - - /** - * Construct the class and check for - * the DOMDocument extension - * - * @param string $config - * @author Sam Clark - */ - protected function __construct($config) - { - // Setup the parent - parent::__construct($config); - - // Check for dom document - if ( ! class_exists('DOMDocument', FALSE)) - throw new Gravatar_Exception_Xmlrpc('DOMDocument is required to use this class'); - } - - /** - * Checks that a hash exists - * - * @param array $hashes - * @return array - * @access public - * @todo - */ - public function exists($hashes) - { - - } - - /** - * Returns an array of email addresses - * registered to the account API key - * - * @return array - * @access public - * @todo - */ - public function addresses() - { - - } - - /** - * Returns an array containing images - * registered to this user - and their - * respective rating - * - * @return array - * @access public - * @todo - */ - public function userimages() - { - - } - - /** - * Save an image to the registered account. - * Images must be transferred in raw base64 - * encoded format. - * - * @param string $image - * @param int $rating [Optional] - * @return string|boolean - * @todo - */ - public function save_data($image, $rating = 0) - { - - } - - /** - * Save a URL to the registered account. - * - * @param string $url - * @param int $rating [Optional] - * @return string|boolean - * @todo - */ - public function save_url($url, $rating = 0) - { - - } - - /** - * Assign a user image on Gravatar to the addresses - * supplied. - * - * @param string $user_image - * @param array $addresses - * @return array - * @access public - * @todo - */ - public function use_userimage($user_image, $addresses) - { - - } - - /** - * Test function - * - * @return mixed - * @access public - * @todo - */ - public function test() - { - - } -} // End Gravatar_Xmlrpc_Dom extends Gravatar_Xmlrpc \ No newline at end of file
samsoir/kohana-gravatar
3e8ec92c7b5db503cbe99ff203ccc7204c957f0c
Fixed size validation: is_numeric() will allow many things you don't want here (e.g. floats or hexadecimals); using ctype_digit() now and casting the value to integer afterwards.
diff --git a/classes/gravatar.php b/classes/gravatar.php index 50bace4..d7fd802 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -1,335 +1,335 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar for Kohana PHP 3 * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ */ class Gravatar { /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function & instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); // Return a the instance return self::$_instances[$email][$config_checksum]; } /** * Factory method * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function factory($email, $config = NULL) { return new Gravatar($email, $config); } /** * Gravatar Ratings constants */ const GRAVATAR_G = 'G'; const GRAVATAR_PG = 'PG'; const GRAVATAR_R = 'R'; const GRAVATAR_X = 'X'; /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array * @access protected */ protected $_attributes = array(); /** * The email address of the user * * @var string * @access protected */ protected $_email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address $this->email($email); if (empty($config)) $this->_config = Kohana::config('gravatar.default'); elseif (is_array($config)) { // Setup the configuration $config += Kohana::config('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { if ($config = Kohana::config('gravatar.'.$config) === NULL) throw new Gravatar_Exception(printf('Gravatar.__construct() , Invalid configuration group name : %s', $config)); $this->_config = $config; } } /** * __get() magic method for accessing email value * * @param mixed key the key to get * @return mixed the returned value * @access public */ public function __get($key) { if ($key === 'email') { $key = '_'.$key; return $this->$key; } elseif ($this->config[$key] !== NULL) return $this->_config[$key]; elseif ($this->attributes[$key] !== NULL) return $this->_attributes[$key]; else return NULL; } /** * __set() magic method for setting object properties * If $var is a method then this will call it, else it will * set the attribute $key = $value * * @param string $key * @param string $value * @return void * @author Sam Clark */ public function __set($key, $value) { if ($key === 'email') { $key = '_'.$key; $this->$key; } else $result = $this->add_attribute($key, $value); } /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } /** * Accessor method for setting email address * * @param string email the valid email address of Gravatar user * @return self * @access public * @author Sam Clark */ public function email($email) { if (validate::email($email)) $this->_email = strtolower($email); else throw new Gravatar_Exception(printf('The email address %s is incorrectly formatted', $email)); return $this; } /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self * @access public * @author Sam Clark */ public function size($size) { - if (is_numeric($size) AND $size > 0) - $this->_config['size'] = $size; + if (ctype_digit((string) $size)) + $this->_config['size'] = (int) $size; else throw new Gravatar_Exception('The image size must be greater than zero'); return $this; } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self * @access public * @author Sam Clark */ public function rating($rating) { if (in_array(strtoupper($rating), array('G', 'PG', 'R', 'X'))) $this->_config['rating'] = strtoupper($rating); else throw new Gravatar_Exception(printf('The rating value %s is not valid. Please use G, PG, R or X. Also available through Class constants'), $rating); return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self * @access public * @author Sam Clark */ public function default_image($url) { if (validate::url($url)) $this->_config['default'] = $url; else throw new Gravatar(printf('The url %s is improperly formatted', $url)); return $this; } /** * Allows addition of custom HTML attributes such as 'id' or 'class'. * * @param string key the attribute key * @param string value the attribute value * @return self * @access public * @author Sam Clark */ public function add_attribute($key, $value) { $this->_attributes[$key] = $value; return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public * @author Sam Clark */ public function render($view = FALSE, $email = NULL) { if (isset($email)) $this->email($email); $data = array('src' => array('src' => $this->_generate_url())); if ($this->_attributes) $data['src'] += $this->_attributes; $data['alt'] = $this->_process_alt(); return (string) $view ? new View($view, $data) : new View($this->_config['view'], $data);; } /** * Process the alt attribute output * * @return string * @access protected * @author Sam Clark */ protected function _process_alt() { $keys = array ( '{$email}' => $this->_email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) $alt = strtr($this->_config['alt'], $keys); else $alt = FALSE; return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected * @author Sam Clark */ protected function _generate_url() { $string = $this->_config['service'].'?gravatar_id='.md5($this->_email).'&s='.$this->_config['size'].'&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) $string .= '&d='.$this->_config['default']; return $string; } } \ No newline at end of file
samsoir/kohana-gravatar
e6b2433b22914aa832328d55bc5322231a8e9d26
Fixing parse errors
diff --git a/classes/gravatar.php b/classes/gravatar.php index c4561c1..50bace4 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -1,335 +1,335 @@ <?php defined('SYSPATH') or die('No direct script access.'); /** * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. * Users must register their email addresses with Gravatar before their avatars will be * usable with this module. Users with gravatars can have a default image of your selection. * * [ref-gravatar]: http://en.gravatar.com/ * * @package Gravatar for Kohana PHP 3 * @author Sam C. De Freyssinet * @copyright (c) 2009 De Freyssinet * @version 3.0.0 * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ */ class Gravatar { /** * Static instances * * @var array * @static * @access protected */ static protected $_instances = array(); /** * Instance constructor pattern * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function & instance($email, $config = NULL) { // Create an instance checksum $config_checksum = sha1(serialize($config)); // Load the Gravatar instance for email and configuration if ( ! isset(self::$_instances[$email][$config_checksum])) self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); // Return a the instance return self::$_instances[$email][$config_checksum]; } /** * Factory method * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @return Gravatar * @access public * @static */ public static function factory($email, $config = NULL) { return new Gravatar($email, $config); } /** * Gravatar Ratings constants */ const GRAVATAR_G = 'G'; const GRAVATAR_PG = 'PG'; const GRAVATAR_R = 'R'; const GRAVATAR_X = 'X'; /** * Configuration for this library, merged with the static config * * @var array * @access protected */ protected $_config; /** * Additional attributes to add to the image * * @var array * @access protected */ protected $_attributes = array(); /** * The email address of the user * * @var string * @access protected */ protected $_email; /** * Gravatar constructor * * @param string email the Gravatar to fetch for email address * @param string config the name of the configuration grouping * @param array config array of key value configuration pairs * @access public * @throws Gravatar_Exception */ protected function __construct($email, $config = NULL) { // Set the email address $this->email($email); if (empty($config)) $this->_config = Kohana::config('gravatar.default'); elseif (is_array($config)) { // Setup the configuration $config += Kohana::config('gravatar.default'); $this->_config = $config; } elseif (is_string($config)) { if ($config = Kohana::config('gravatar.'.$config) === NULL) - throw new Gravatar_Exception(printf('Gravatar.__construct() , Invalid configuration group name : %s', $config); + throw new Gravatar_Exception(printf('Gravatar.__construct() , Invalid configuration group name : %s', $config)); $this->_config = $config; } } /** * __get() magic method for accessing email value * * @param mixed key the key to get * @return mixed the returned value * @access public */ public function __get($key) { if ($key === 'email') { $key = '_'.$key; return $this->$key; } elseif ($this->config[$key] !== NULL) return $this->_config[$key]; elseif ($this->attributes[$key] !== NULL) return $this->_attributes[$key]; else return NULL; } /** * __set() magic method for setting object properties * If $var is a method then this will call it, else it will * set the attribute $key = $value * * @param string $key * @param string $value * @return void * @author Sam Clark */ public function __set($key, $value) { - if ($key === 'email')) + if ($key === 'email') { $key = '_'.$key; $this->$key; } else $result = $this->add_attribute($key, $value); } /** * Handles this object being cast to string * * @return string the resulting Gravatar * @access public * @author Sam Clark */ public function __toString() { return (string) $this->render(); } /** * Accessor method for setting email address * * @param string email the valid email address of Gravatar user * @return self * @access public * @author Sam Clark */ public function email($email) { if (validate::email($email)) $this->_email = strtolower($email); else - throw new Gravatar_Exception(printf('The email address %s is incorrectly formatted', $email); + throw new Gravatar_Exception(printf('The email address %s is incorrectly formatted', $email)); return $this; } /** * Accessor method for setting size of gravatar * * @param int size the size of the gravatar image in pixels * @return self * @access public * @author Sam Clark */ public function size($size) { if (is_numeric($size) AND $size > 0) $this->_config['size'] = $size; else throw new Gravatar_Exception('The image size must be greater than zero'); return $this; } /** * Accessor method for the rating of the gravatar * * @param string rating the rating of the gravatar * @return self * @access public * @author Sam Clark */ public function rating($rating) { if (in_array(strtoupper($rating), array('G', 'PG', 'R', 'X'))) $this->_config['rating'] = strtoupper($rating); else throw new Gravatar_Exception(printf('The rating value %s is not valid. Please use G, PG, R or X. Also available through Class constants'), $rating); return $this; } /** * Accessor method for setting the default image if the supplied email address or rating return an empty result * * @param string url the url of the image to use instead of the Gravatar * @return self * @access public * @author Sam Clark */ public function default_image($url) { if (validate::url($url)) $this->_config['default'] = $url; else - throw new Gravatar(printf('The url %s is improperly formatted', $url); + throw new Gravatar(printf('The url %s is improperly formatted', $url)); return $this; } /** * Allows addition of custom HTML attributes such as 'id' or 'class'. * * @param string key the attribute key * @param string value the attribute value * @return self * @access public * @author Sam Clark */ public function add_attribute($key, $value) { $this->_attributes[$key] = $value; return $this; } /** * Renders the Gravatar using supplied configuration and attributes. Can use custom view. * * @param string view [Optional] a kohana PHP * @param string email [Optional] the valid email of a Gravatar user * @return string the rendered Gravatar output * @access public * @author Sam Clark */ public function render($view = FALSE, $email = NULL) { if (isset($email)) $this->email($email); $data = array('src' => array('src' => $this->_generate_url())); if ($this->_attributes) $data['src'] += $this->_attributes; $data['alt'] = $this->_process_alt(); return (string) $view ? new View($view, $data) : new View($this->_config['view'], $data);; } /** * Process the alt attribute output * * @return string * @access protected * @author Sam Clark */ protected function _process_alt() { $keys = array ( '{$email}' => $this->_email, '{$size}' => $this->_config['size'], '{$rating}' => $this->_config['rating'], ); if ($this->_config['alt']) $alt = strtr($this->_config['alt'], $keys); else $alt = FALSE; return $alt; } /** * Creates the Gravatar URL based on the configuration and email * * @return string the resulting Gravatar URL * @access protected * @author Sam Clark */ protected function _generate_url() { $string = $this->_config['service'].'?gravatar_id='.md5($this->_email).'&s='.$this->_config['size'].'&r='.$this->_config['rating']; if ( ! empty($this->_config['default'])) $string .= '&d='.$this->_config['default']; return $string; } } \ No newline at end of file
samsoir/kohana-gravatar
c76d7ebc158bce91ca8dd5ecbc48d1a0fa8bab09
Work in progress on the new Gavatar API for managing your Gravatar account externally
diff --git a/classes/gravatar/exception/xmlrpc.php b/classes/gravatar/exception/xmlrpc.php new file mode 100644 index 0000000..d11cb6d --- /dev/null +++ b/classes/gravatar/exception/xmlrpc.php @@ -0,0 +1,10 @@ +<?php defined('SYSPATH') or die('No direct script access.'); + +class Gravatar_Exception_Xmlrpc extends Gravatar_Exception { + + public function __construct($message, $code = NULL) + { + parent::__construct($message, NULL, $code); + } + +} \ No newline at end of file diff --git a/classes/gravatar/xmlrpc.php b/classes/gravatar/xmlrpc.php new file mode 100644 index 0000000..14025a2 --- /dev/null +++ b/classes/gravatar/xmlrpc.php @@ -0,0 +1,199 @@ +<?php defined('SYSPATH') or die('No direct script access.'); +/** + * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. + * Users must register their email addresses with Gravatar before their avatars will be + * usable with this module. Users with gravatars can have a default image of your selection. + * + * [ref-gravatar]: http://en.gravatar.com/ + * + * @package Gravatar XMLRPC API for Kohana PHP 3 + * @author Sam C. De Freyssinet + * @copyright (c) 2009 De Freyssinet + * @version 3.0.0 + * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ + * @abstract + */ +abstract class Gravatar_Xmlrpc { + + /** + * Create an instance of the Gravatar XMLRPC API client + * + * @param array $config + * @return self + * @access public + * @static + */ + public static function instance($config = array()) + { + static $instance; + + empty($instance) and $instance = new Gravatar_Xmlrpc($config); + + return $instance; + } + + /** + * Factory method for creating a new Xmlrpc object + * + * @param array $config + * @return self + * @access public + * @static + */ + public static function factory($config = array()) + { + return new Gravatar_Xmlrpc($config); + } + + /** + * Configuration for this client + * + * @var array + */ + protected $_config; + + /** + * Constructor, maintains the singleton or factory pattern + * + * @param array $config + * @access protected + */ + protected function __construct($config) + { + // Configure this library + $config += Kohana::config('gravatar.xmlrpc'); + $this->_config = $config; + } + + /** + * Set or get the api_key + * + * @param string $api_key + * @return string|self + * @access public + */ + public function api_key($api_key = NULL) + { + // If there is no API key supplied + if ($api_key === NULL) + return $this->_config['api_key']; + + // Else set the API key + $this->_config['api_key'] = (string) $api_key; + + // Return this + return $this; + } + + /** + * Set or get the email address in question + * + * @param string $email [Optional] + * @return string|self + * @access public + */ + public function email($email = NULL) + { + // If no argument, return the email address + if ($email === NULL) + return $this->_config['email']; + + // Set the email address + $this->_config['email']; + + // Return this + return $this; + } + + /** + * Checks that a hash exists + * + * @param array $hashes + * @return array + * @access public + * @abstract + */ + abstract public function exists($hashes); + + /** + * Returns an array of email addresses + * registered to the account API key + * + * @return array + * @access public + * @abstract + */ + abstract public function addresses(); + + /** + * Returns an array containing images + * registered to this user - and their + * respective rating + * + * @return array + * @access public + * @abstract + */ + abstract public function userimages(); + + /** + * Save an image to the registered account. + * Images must be transferred in raw base64 + * encoded format. + * + * @param string $image + * @param int $rating [Optional] + * @return string|boolean + * @access public + * @abstract + */ + abstract public function save_data($image, $rating = 0); + + /** + * Save a URL to the registered account. + * + * @param string $url + * @param int $rating [Optional] + * @return string|boolean + * @access public + * @abstract + */ + abstract public function save_url($url, $rating = 0); + + /** + * Assign a user image on Gravatar to the addresses + * supplied. + * + * @param string $user_image + * @param array $addresses + * @return array + * @access public + * @abstract + */ + abstract public function use_userimage($user_image, $addresses); + + /** + * Test function + * + * @return mixed + * @access public + * @abstract + */ + abstract public function test(); + + /** + * Execute the Xmlrpc request and return + * the result + * + * @param string $xml + * @return mixed + * @access protected + */ + protected function _exec($xml) + { + // Create the URL + $url = $this->_config['service'].md5($this->_config['email']); + + $result = Remote::get() + } +} \ No newline at end of file diff --git a/classes/gravatar/xmlrpc/dom.php b/classes/gravatar/xmlrpc/dom.php new file mode 100644 index 0000000..3f90a8f --- /dev/null +++ b/classes/gravatar/xmlrpc/dom.php @@ -0,0 +1,93 @@ +<?php defined('SYSPATH') or die('No direct script access.'); + +class Gravatar_Xmlrpc_Dom extends Gravatar_Xmlrpc { + + /** + * Construct the class and check for + * the DOMDocument extension + * + * @param string $config + * @author Sam Clark + */ + protected function __construct($config) + { + // Setup the parent + parent::__construct($config); + + // Check for dom document + if ( ! class_exists('DOMDocument', FALSE)) + throw new Gravatar_Exception_Xmlrpc('DOMDocument is required to use this class'); + } + + /** + * Checks that a hash exists + * + * @param array $hashes + * @return array + * @access public + * @abstract + */ + public function exists($hashes); + + /** + * Returns an array of email addresses + * registered to the account API key + * + * @return array + * @access public + * @abstract + */ + public function addresses(); + + /** + * Returns an array containing images + * registered to this user - and their + * respective rating + * + * @return array + * @access public + * @abstract + */ + public function userimages(); + + /** + * Save an image to the registered account. + * Images must be transferred in raw base64 + * encoded format. + * + * @param string $image + * @param int $rating [Optional] + * @return string|boolean + * @access public + */ + public function save_data($image, $rating = 0); + + /** + * Save a URL to the registered account. + * + * @param string $url + * @param int $rating [Optional] + * @return string|boolean + * @access public + */ + public function save_url($url, $rating = 0); + + /** + * Assign a user image on Gravatar to the addresses + * supplied. + * + * @param string $user_image + * @param array $addresses + * @return array + * @access public + */ + public function use_userimage($user_image, $addresses); + + /** + * Test function + * + * @return mixed + * @access public + */ + public function test(); +} // End Gravatar_Xmlrpc_Dom extends Gravatar_Xmlrpc \ No newline at end of file diff --git a/config/gravatar.php b/config/gravatar.php index 2aeb593..53d22a5 100644 --- a/config/gravatar.php +++ b/config/gravatar.php @@ -1,12 +1,17 @@ <?php defined('SYSPATH') or die('No direct script access.'); return array( 'default' => array( 'service' => 'http://www.gravatar.com/avatar.php', // The gravatar service URL 'default_image' => FALSE, // The default image if Gravatar is not found, FALSE uses Gravatar default 'size' => 100, // The size of the returned gravatar 'view' => 'gravatar/image', // The default view 'rating' => Gravatar::GRAVATAR_G, // The default rating 'alt' => FALSE, // Alternate image string, FALSE to omit, string to include - ) + ), + 'xmlrpc' => array( + 'service' => 'https://secure.gravatar.com/xmlrpc?user=', + 'api_key' => '', + 'email' => '', + ), ); \ No newline at end of file
samsoir/kohana-gravatar
98206d312b7042e86bcbc9db11043e82237085a6
Gravatar class, refactored for Kohana 3
diff --git a/classes/gravatar.php b/classes/gravatar.php index e69de29..c4561c1 100644 --- a/classes/gravatar.php +++ b/classes/gravatar.php @@ -0,0 +1,335 @@ +<?php defined('SYSPATH') or die('No direct script access.'); +/** + * [ref-gravatar] Gravatars are universal avatars available to all web sites and services. + * Users must register their email addresses with Gravatar before their avatars will be + * usable with this module. Users with gravatars can have a default image of your selection. + * + * [ref-gravatar]: http://en.gravatar.com/ + * + * @package Gravatar for Kohana PHP 3 + * @author Sam C. De Freyssinet + * @copyright (c) 2009 De Freyssinet + * @version 3.0.0 + * @license http://creativecommons.org/licenses/by-sa/2.0/uk/ + */ +class Gravatar { + + /** + * Static instances + * + * @var array + * @static + * @access protected + */ + static protected $_instances = array(); + + /** + * Instance constructor pattern + * + * @param string email the Gravatar to fetch for email address + * @param string config the name of the configuration grouping + * @param array config array of key value configuration pairs + * @return Gravatar + * @access public + * @static + */ + public static function & instance($email, $config = NULL) + { + // Create an instance checksum + $config_checksum = sha1(serialize($config)); + + // Load the Gravatar instance for email and configuration + if ( ! isset(self::$_instances[$email][$config_checksum])) + self::$_instances[$email][$config_checksum] = new Gravatar($email, $config); + + // Return a the instance + return self::$_instances[$email][$config_checksum]; + } + + /** + * Factory method + * + * @param string email the Gravatar to fetch for email address + * @param string config the name of the configuration grouping + * @param array config array of key value configuration pairs + * @return Gravatar + * @access public + * @static + */ + public static function factory($email, $config = NULL) + { + return new Gravatar($email, $config); + } + + /** + * Gravatar Ratings constants + */ + const GRAVATAR_G = 'G'; + const GRAVATAR_PG = 'PG'; + const GRAVATAR_R = 'R'; + const GRAVATAR_X = 'X'; + + /** + * Configuration for this library, merged with the static config + * + * @var array + * @access protected + */ + protected $_config; + + /** + * Additional attributes to add to the image + * + * @var array + * @access protected + */ + protected $_attributes = array(); + + /** + * The email address of the user + * + * @var string + * @access protected + */ + protected $_email; + + /** + * Gravatar constructor + * + * @param string email the Gravatar to fetch for email address + * @param string config the name of the configuration grouping + * @param array config array of key value configuration pairs + * @access public + * @throws Gravatar_Exception + */ + protected function __construct($email, $config = NULL) + { + // Set the email address + $this->email($email); + + if (empty($config)) + $this->_config = Kohana::config('gravatar.default'); + elseif (is_array($config)) + { + // Setup the configuration + $config += Kohana::config('gravatar.default'); + $this->_config = $config; + } + elseif (is_string($config)) + { + if ($config = Kohana::config('gravatar.'.$config) === NULL) + throw new Gravatar_Exception(printf('Gravatar.__construct() , Invalid configuration group name : %s', $config); + + $this->_config = $config; + } + } + + /** + * __get() magic method for accessing email value + * + * @param mixed key the key to get + * @return mixed the returned value + * @access public + */ + public function __get($key) + { + if ($key === 'email') + { + $key = '_'.$key; + return $this->$key; + } + elseif ($this->config[$key] !== NULL) + return $this->_config[$key]; + elseif ($this->attributes[$key] !== NULL) + return $this->_attributes[$key]; + else + return NULL; + } + + /** + * __set() magic method for setting object properties + * If $var is a method then this will call it, else it will + * set the attribute $key = $value + * + * @param string $key + * @param string $value + * @return void + * @author Sam Clark + */ + public function __set($key, $value) + { + if ($key === 'email')) + { + $key = '_'.$key; + $this->$key; + } + else + $result = $this->add_attribute($key, $value); + + } + + /** + * Handles this object being cast to string + * + * @return string the resulting Gravatar + * @access public + * @author Sam Clark + */ + public function __toString() + { + return (string) $this->render(); + } + + /** + * Accessor method for setting email address + * + * @param string email the valid email address of Gravatar user + * @return self + * @access public + * @author Sam Clark + */ + public function email($email) + { + if (validate::email($email)) + $this->_email = strtolower($email); + else + throw new Gravatar_Exception(printf('The email address %s is incorrectly formatted', $email); + + return $this; + } + + /** + * Accessor method for setting size of gravatar + * + * @param int size the size of the gravatar image in pixels + * @return self + * @access public + * @author Sam Clark + */ + public function size($size) + { + if (is_numeric($size) AND $size > 0) + $this->_config['size'] = $size; + else + throw new Gravatar_Exception('The image size must be greater than zero'); + + return $this; + } + + /** + * Accessor method for the rating of the gravatar + * + * @param string rating the rating of the gravatar + * @return self + * @access public + * @author Sam Clark + */ + public function rating($rating) + { + if (in_array(strtoupper($rating), array('G', 'PG', 'R', 'X'))) + $this->_config['rating'] = strtoupper($rating); + else + throw new Gravatar_Exception(printf('The rating value %s is not valid. Please use G, PG, R or X. Also available through Class constants'), $rating); + + return $this; + } + + /** + * Accessor method for setting the default image if the supplied email address or rating return an empty result + * + * @param string url the url of the image to use instead of the Gravatar + * @return self + * @access public + * @author Sam Clark + */ + public function default_image($url) + { + if (validate::url($url)) + $this->_config['default'] = $url; + else + throw new Gravatar(printf('The url %s is improperly formatted', $url); + + return $this; + } + + /** + * Allows addition of custom HTML attributes such as 'id' or 'class'. + * + * @param string key the attribute key + * @param string value the attribute value + * @return self + * @access public + * @author Sam Clark + */ + public function add_attribute($key, $value) + { + $this->_attributes[$key] = $value; + + return $this; + } + + /** + * Renders the Gravatar using supplied configuration and attributes. Can use custom view. + * + * @param string view [Optional] a kohana PHP + * @param string email [Optional] the valid email of a Gravatar user + * @return string the rendered Gravatar output + * @access public + * @author Sam Clark + */ + public function render($view = FALSE, $email = NULL) + { + if (isset($email)) + $this->email($email); + + $data = array('src' => array('src' => $this->_generate_url())); + + if ($this->_attributes) + $data['src'] += $this->_attributes; + + $data['alt'] = $this->_process_alt(); + + return (string) $view ? new View($view, $data) : new View($this->_config['view'], $data);; + } + + /** + * Process the alt attribute output + * + * @return string + * @access protected + * @author Sam Clark + */ + protected function _process_alt() + { + $keys = array + ( + '{$email}' => $this->_email, + '{$size}' => $this->_config['size'], + '{$rating}' => $this->_config['rating'], + ); + + if ($this->_config['alt']) + $alt = strtr($this->_config['alt'], $keys); + else + $alt = FALSE; + + return $alt; + } + + /** + * Creates the Gravatar URL based on the configuration and email + * + * @return string the resulting Gravatar URL + * @access protected + * @author Sam Clark + */ + protected function _generate_url() + { + $string = $this->_config['service'].'?gravatar_id='.md5($this->_email).'&s='.$this->_config['size'].'&r='.$this->_config['rating']; + + if ( ! empty($this->_config['default'])) + $string .= '&d='.$this->_config['default']; + + return $string; + } +} \ No newline at end of file
samsoir/kohana-gravatar
3874f2d1bc900face6bfeb6954184a802ccefba9
Added the Gravatar config and class files. Refactored for Kohana 3
diff --git a/classes/gravatar/exception.php b/classes/gravatar/exception.php new file mode 100644 index 0000000..7a4e4d1 --- /dev/null +++ b/classes/gravatar/exception.php @@ -0,0 +1,3 @@ +<?php defined('SYSPATH') or die('No direct script access.'); + +class Gravatar_Exception extends Kohana_Exception { } \ No newline at end of file diff --git a/config/gravatar.php b/config/gravatar.php new file mode 100644 index 0000000..2aeb593 --- /dev/null +++ b/config/gravatar.php @@ -0,0 +1,12 @@ +<?php defined('SYSPATH') or die('No direct script access.'); + +return array( + 'default' => array( + 'service' => 'http://www.gravatar.com/avatar.php', // The gravatar service URL + 'default_image' => FALSE, // The default image if Gravatar is not found, FALSE uses Gravatar default + 'size' => 100, // The size of the returned gravatar + 'view' => 'gravatar/image', // The default view + 'rating' => Gravatar::GRAVATAR_G, // The default rating + 'alt' => FALSE, // Alternate image string, FALSE to omit, string to include + ) +); \ No newline at end of file
samsoir/kohana-gravatar
28ef1dc1cceab96c43633d927c05947e106f8eac
Added the gravatar.php file to Git
diff --git a/classes/gravatar.php b/classes/gravatar.php new file mode 100644 index 0000000..e69de29
Jermuk/custom_cs2dsrv
c4f76cadf18a33729d2885d9930f328c188cdbe6
Works now with the actual version of cs2d
diff --git a/.gitignore b/.gitignore index ee50cdf..82715a6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,14 @@ html Debug .settings .cproject .project doxygen.Doxyfile *.txt Release/src *.map *.cfg -notices \ No newline at end of file +notices +*.o +custom_cs2dsrv.dev +Makefile.win \ No newline at end of file diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe index d9325ce..40e9f4d 100644 Binary files a/Release/custom_cs2dsrv.exe and b/Release/custom_cs2dsrv.exe differ diff --git a/src/main.c b/src/main.c index bc09eeb..8e15b13 100644 --- a/src/main.c +++ b/src/main.c @@ -1,300 +1,300 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, FloooD */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, sv_hostport); atexit(cleanup); //struct in_addr usgnip = GetIp("usgn.de"); /* FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); */ OnServerStart(); ReadMap(); - UsgnRegister(readsocket); + //UsgnRegister(readsocket); /** * \var needed for ExecuteFunctionsWithTime() */ time_t checktime; time(&checktime); int mstime = mtime(); int timecounter = mtime(); int tickcounter = 0; const int fps = 1000 / sv_fps; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; //1ms = 1000 while (1) { if ((timecounter + 1000 - (int) mtime()) <= 0) { fpsnow = (int) tickcounter; tickcounter = 0; timecounter = mtime(); } tickcounter++; UpdateBuffer(); CheckForTimeout(readsocket); ExecuteFunctionsWithTime(&checktime, readsocket); CheckAllPlayerForReload(readsocket); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); select(readsocket + 1, &descriptor, NULL, NULL, &timeout); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation player[id].lastpaket = mtime(); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 24: rtn = drop(message, tempsize, id, readsocket); break; case 28: // Spray 28 - 0 - x x - y y - color rtn = spray(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 236: rtn = rcon_pw(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 27: rtn = UsgnPacket(27, message, tempsize, readsocket); break; case 28: rtn = UsgnPacket(28, message, tempsize, readsocket); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } #ifdef _WIN32 Sleep(fps + mstime - mtime()); #else sleep(fps + mstime - mtime()); #endif mstime = mtime(); } return EXIT_SUCCESS; } diff --git a/src/pakets.c b/src/pakets.c index eae7fb4..fdf5f67 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -703,1165 +703,1217 @@ int joinroutine_unknown(unsigned char *message, int length, int i; for (i = 1; i <= MAX_CLIENTS - 1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + u_strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if (paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch (OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength = 4; unsigned char team, unknown; int paketsize; if (paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length - position + 1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( chatmessage() )\n"); memcpy(string, message + position, paketsize); string[paketsize] = '\0'; position += paketsize; switch (OnChatMessage(id, string, team, writesocket)) { case 0: SendChatMessage(id, string, team, writesocket); break; case 1: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch (message[1]) { case 0: { paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if (player[id].joinstatus == 1) { paketlength = 16; // ??? if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; player[id].name = malloc(stringsize + 1); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message + position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; unsigned char *password = malloc(stringsize + 1); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message + position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; for (i = 0; i <= u_strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; unsigned char *encryption1 = malloc(stringsize + 1); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message + position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message + position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes /* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif */ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; player[id].spraylogo = malloc(stringsize + 1); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message + position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; unsigned char *maphash = malloc(stringsize + 1); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; player[id].win = malloc(stringsize + 1); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message + position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch (tempstatus) { case 0x00: stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); position += u_strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } //stringsize = 16 + u_strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if (stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if (player[id].joinstatus == 2) { int position = 2; paketlength = 5; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } position++; unsigned char *maphash = malloc(stringsize + 1); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMaphash: %s\n", maphash); //pre_authcode_respond stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("pre_authcon_respond too big\n"); return length; } position++; unsigned char *pre_authcode_respond = malloc(stringsize + 1); if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(pre_authcode_respond, message + position, stringsize); pre_authcode_respond[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); //Player Version //unsigned char mapstatus = message[position]; //avoid warning position++; //printf("\tMapstatus: %d\n", mapstatus); free(pre_authcode_respond); free(maphash); //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if (player[id].joinstatus == 3) { int position = 2; paketlength = 3; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Mapname too big\n"); return length; } position++; unsigned char *mapname = malloc(stringsize + 1); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message + position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- - stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); + stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name) + 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(sv_name); position++; memcpy(buffer + position, sv_name, u_strlen(sv_name)); position += u_strlen(sv_name); buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_friendlyfire; position++; buffer[position] = 0; //Unknown position++; buffer[position] = mp_roundtime; position++; buffer[position] = mp_freezetime; position++; buffer[position] = mp_c4timer; position++; buffer[position] = 32; //Unknown position++; buffer[position] = 124; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 1; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_maxplayers; position++; buffer[position] = sv_fow; position++; buffer[position] = mp_specmode; position++; buffer[position] = sv_gamemode; position++; buffer[position] = mp_respawndelay; position++; buffer[position] = mp_infammo; position++; + + buffer[position] = 1; //01 + position++; + buffer[position] = 8; //08 + position++; + buffer[position] = 51; //33 + position++; + buffer[position] = 58; //3A + position++; + buffer[position] = 11; //0B + position++; + buffer[position] = 22; //16 + position++; + buffer[position] = 32; //20 + position++; + buffer[position] = 35; //23 + position++; + buffer[position] = 80; //50 + position++; + buffer[position] = 73; //49 + position++; + buffer[position] = 0; //00 + position++; + + buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; +/* + 0a 00 fc 06 00 07 ...c...>.7...... +0030 64 65 5f 64 75 73 74 06 53 65 72 76 65 72 00 00 de_dust.Server.. +0040 00 00 05 00 23 1e f3 03 00 01 00 06 01 01 00 00 ....#........... +0050 00 01 08 33 3a 0b 16 20 23 50 49 00 03 41 43 4b ...3:.. #PI..ACK + +*/ SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; position++; buffer[position] = onlineplayer; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 1 && i != id) { unsigned char *encodedname; encodedname = GetEncodedString(player[i].name, u_strlen( player[i].name)); unsigned short *deaths = &player[i].deaths; unsigned short tempscore = (unsigned) (player[i].deaths + 1000); unsigned short *score = &tempscore; unsigned short tempx = (player[i].x); unsigned short tempy = (player[i].y); unsigned short *x = &tempx; unsigned short *y = &tempy; float *ptemprotation = &player[i].rotation; int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = i; position++; buffer[position] = u_strlen(encodedname); position++; memcpy(buffer + position, encodedname, u_strlen(encodedname)); position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[i].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = player[i].skin; //Unknown position++; /* buffer[position] = score[0]; //Deaths position++; buffer[position] = score[1]; //Deaths position++; */ memcpy(buffer + position, score, 2); position += 2; /* buffer[position] = deaths[0]; //Deaths position++; buffer[position] = deaths[1]; //Deaths position++; */ memcpy(buffer + position, deaths, 2); position += 2; memcpy(buffer + position, x, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; memcpy(buffer + position, y, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = ptemprotation[0]; //Rotation position++; buffer[position] = ptemprotation[1]; //Rotation position++; buffer[position] = player[i].health; //Health position++; buffer[position] = player[i].armor; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe position++; buffer[position] = 0; //Unknown position++; /* 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 e8 03 00 00 12 01 00 00 01 03 e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 */ } } if (1) { unsigned char *encodedname; encodedname = GetEncodedString(player[id].name, u_strlen( player[id].name)); int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = id; position++; buffer[position] = u_strlen(encodedname); position++; memcpy(buffer + position, encodedname, u_strlen(encodedname)); position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[id].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 232; //Unknown position++; buffer[position] = 3; //Unknown position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //X position++; buffer[position] = 0; //X position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Health position++; buffer[position] = 0; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Aktuelle Waffe 50 = Knife position++; buffer[position] = 0; //Unknown position++; } SendToPlayer(buffer, position, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- HostageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 2; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ItemData ----------- /* fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 */ stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 3; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- EnityData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 4; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 5; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ProjectileData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 6; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectImageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 7; //third payload position++; buffer[position] = 0; position++; + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- TweenData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 8; //third payload + position++; + buffer[position] = 0; + position++; + SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- Final ACK ----------- stringsize = 7; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 200; //third payload position++; buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); player[id].joinstatus = 4; free(mapname); OnJoin(id, writesocket); } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } default: { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } return paketlength; } int leave(int id, int writesocket) { OnLeave(id, writesocket); free(player[id].name); free(player[id].usgn); free(player[id].spraylogo); free(player[id].win); player[id].name = NULL; player[id].usgn = NULL; player[id].spraylogo = NULL; player[id].win = NULL; onlineplayer--; ClearPlayer(id); return 2; } int reload(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int status; status = message[position]; position++; if (status == 1) { SendReloadMessage(id, 1, writesocket); player[id].reloading = player[id].actualweapon; player[id].reloadtimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].reloadtime; } return paketlength; } int spray(unsigned char *message, int length, int id, int writesocket) { // 28 0 xx yy c // 0 1 23 45 6 struct { unsigned char hi; unsigned char lo; } x, y; if (length < 7) { printf("Invalid packet (spray)!\n"); return length; } x.lo = message[2]; x.hi = message[3]; y.lo = message[4]; y.hi = message[5]; unsigned short xx = x.hi * 256 + x.lo, yy = y.hi * 256 + y.lo; unsigned char c = message[6]; unsigned char i = (char) id; // Postprocessing if needed, then send back exact same data // xx and yy are positions, not tiles. SendSprayMessage(i, xx, yy, c, writesocket); return 7; } int UsgnPacket(int packetid, unsigned char *message, int length, int writesocket) //No check if really from usgn.de { int paketlength = 2; switch (packetid) { case 27: if (message[1] == 1) { printf("[USGN] Server successfully added to the serverlist..\n"); } else { printf("[USGN] Server NOT added to the serverlist.. (Code: %d)\n", message[3]); } paketlength = 2; break; case 28: if (message[1] == 2) { printf("[USGN] Server successfully updated in the serverlist..\n"); } else { printf("[USGN] Server NOT updated in the serverlist.. (Code: %d)\n", message[3]); } paketlength = 2; break; default: printf("[USGN] Unknown Message recieved: "); int i; for (i = 0; i < length; i++) { eprintf("%d-", message[i]); } eprintf("\n"); paketlength = length; break; } return paketlength; } int drop(unsigned char *message, int length, int id, int writesocket) { int paketlength = 7; if (length < paketlength) { printf("Invalid packet (drop)!\n"); return length; } int position = 1; unsigned char wpnid, unknown1, unknown2, unknown3; unsigned short ammo1, ammo2; wpnid = message[position]; position++; ammo1 = message[position]; position++; unknown1 = message[position]; position++; ammo2 = message[position]; position++; unknown2 = message[position]; position++; unknown3 = message[position]; position++; switch (OnDrop(id, wpnid, ammo1, ammo2, unknown1, unknown2, unknown3, writesocket)) { case 0: RemovePlayerWeapon(id, wpnid); SendDropMessage(id, wpnid, ammo1, ammo2, unknown1, unknown2, unknown3, writesocket); break; default: break; } return paketlength; } int rcon_pw(unsigned char *message, int length, int id, int writesocket) { // 236 ln pw // 0 1 ln unsigned char key[] = "mysecretremotecontrolpmysecret"; int expected = (int) (message[1]); if (length < expected + 2) { printf("Invalid packet (rcon_pw)!\n"); return length; } char* pw = malloc(expected + 1); int i; for (i = 0; i < expected; i++) { //eprintf("%c", message[i+2]- key[i]); pw[i] = (unsigned char) (message[i + 2] - key[i]); } pw[expected] = '\0'; // Check against actual rcon if (strcmp(pw, (char *)sv_rcon) == 0) { printf("[Rcon_pw] Success\n"); player[id].rcon = 1; //SendRconPwMessage(id, message, length, 1, writesocket); } else { printf("[Rcon_pw] Bad attempt by %s.\n", player[id].name); SendRconPwMessage(id, message, length, 0, writesocket); } return length; }
Jermuk/custom_cs2dsrv
3707f42449d36e505ee1cd320766ccb9ba7040c1
Added half-working & buggie drop
diff --git a/include/log.h b/include/log.h index c0df5a4..480d9e3 100644 --- a/include/log.h +++ b/include/log.h @@ -1,86 +1,85 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef LOG_H_INCLUDED #define LOG_H_INCLUDED #include "main.h" void myprintf(char *string, ...); void myprintf2(char *string, ...); /* #define printf(...) file = fopen("log.txt","a+");\ time(&rawtime );\ timeinfo = localtime(&rawtime);\ fprintf(file, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ fprintf(file, __VA_ARGS__);\ printf("[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ printf(__VA_ARGS__);\ fclose(file) #define eprintf(...) file = fopen("log.txt","a+");\ fprintf(file, __VA_ARGS__);\ fprintf(stdout, __VA_ARGS__);\ fclose(file) extern FILE *file; extern time_t rawtime; extern struct tm * timeinfo; */ #define printf(...) myprintf(__VA_ARGS__) #define eprintf(...) myprintf2(__VA_ARGS__) #endif // LOG_H_INCLUDED - /* if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) { if((player[i].x - player[id].x) != 0 && (player[i].y - player[id].y) != 0) { float temprot = player[id].rotation; double angle = atan2(player[i].x - player[id].x, player[i].y - player[id].y) * 180 / PI; double angle2, angle3; if(player[id].rotation < 0) { temprot += 180; } else if(player[id].rotation > 0) { temprot -= 180; } temprot = temprot *-1; double victimangle = atan2(player[id].x - player[i].x, player[id].y - player[i].y) * 180 / PI; double victimangle2 = victimangle + 90; double victimangle3 = victimangle - 90; int xPoint1, yPoint1; int xPoint2, yPoint2; xPoint1 = player[i].x + 16*cos(victimangle2*PI/180); yPoint1 = player[i].y + 16*sin(victimangle2*PI/180); xPoint2 = player[i].x + 16*cos(victimangle3*PI/180); yPoint2 = player[i].y + 16*sin(victimangle3*PI/180); angle2 = atan2(xPoint1 - player[id].x, yPoint1 - player[id].y) * 180 / PI; angle3 = atan2(xPoint2 - player[id].x, yPoint2 - player[id].y) * 180 / PI; printf("(Debug2) %lf: %lf, %lf\n", temprot, angle2, angle3); xP = xM + r*cos(ß) yP = yM + r*sin(ß) if((temprot <= angle2 && temprot >= angle3) || (temprot >= angle2 && temprot <= angle3)) { SendMessageToPlayer(id, "You hit someone!", 1, writesocket); SendMessageToPlayer(i, "You were hitted by someone!", 1, writesocket); OnHit(id, i, writesocket); } //SendMessageToPlayer(id, "Shooting not implemented yet!", 1, writesocket); } } */ diff --git a/include/pakets.h b/include/pakets.h index 5602652..5486528 100644 --- a/include/pakets.h +++ b/include/pakets.h @@ -1,53 +1,56 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef PAKETS_H_INCLUDED #define PAKETS_H_INCLUDED #include "main.h" //#include "" int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position); int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id); int ping_ingame(unsigned char *message, int length, int id, int writesocket); int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int confirmation_known(unsigned char *message, int length, int id, int writesocket); int fire(unsigned char *message, int length, int id, int writesocket); int advanced_fire(unsigned char *message, int length, int id, int writesocket); int buy(unsigned char *message, int length, int id, int writesocket); int rotupdate(unsigned char *message, int length, int id, int writesocket); int posupdatewalk(unsigned char *message, int length, int id, int writesocket); int posupdaterun(unsigned char *message, int length, int id, int writesocket); int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket); -int posrotupdaterun(unsigned char *message, int length, int id, +int + posrotupdaterun(unsigned char *message, int length, int id, int writesocket); int respawnrequest(unsigned char *message, int length, int id, int writesocket); int weaponchange(unsigned char *message, int length, int id, int writesocket); int teamchange(unsigned char *message, int length, int id, int writesocket); int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int specpos(unsigned char *message, int length, int id, int writesocket); int chatmessage(unsigned char *message, int length, int id, int writesocket); int joinroutine_known(unsigned char *message, int length, int id, int writesocket); int leave(int id, int writesocket); int reload(unsigned char *message, int length, int id, int writesocket); int spray(unsigned char *message, int length, int id, int writesocket); -int UsgnPacket(int packetid, unsigned char *message, int length, int writesocket); +int UsgnPacket(int packetid, unsigned char *message, int length, + int writesocket); +int drop(unsigned char *message, int length, int id, int writesocket); #endif // PAKETS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index 705c9f6..761e824 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,39 +1,41 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); void SendAdvancedFireMessage(int id, int status, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, char *message, int status, int writesocket); void SendMessageToAll(char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); void PingAllPlayer(int writesocket); void SendReloadMessage(int id, int status, int writesocket); -void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket); +void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, + int writesocket); void SendKillMessage(int id, int victim, int writesocket); void SendPingList(int writesocket); void SendBuyFailedMessage(int id, int status, int writesocket); - +void SendDropMessage(int id, int wpnid, int ammo1, int ammo2, int unknown1, + int unknown2, int unknown3, int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/script-functions.h b/include/script-functions.h index bb05b5e..a89ca85 100644 --- a/include/script-functions.h +++ b/include/script-functions.h @@ -1,35 +1,38 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef SCRIPT_H_INCLUDED #define SCRIPT_H_INCLUDED #include "main.h" int OnJoin(int id, int writesocket); int OnLeave(int id, int writesocket); int OnSpecmove(int id, int newx, int newy, int writesocket); int OnServerStart(); int OnExit(); int OnRespawnRequest(int id, int writesocket); int OnRespawn(int id, int writesocket); int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); int OnAdvancedFire(int id, int status, int writesocket); int OnFire(int id, int writesocket); int OnHit(int hitter, int victim, int writesocket); int OnBuyAttempt(int id, int wpnid, int writesocket); int OnBuy(int id, int wpnid, int writesocket); int OnKill(int hitter, int victim, int wpnid, int writesocket); int OnChatMessage(int id, unsigned char *message, int team, int writesocket); int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket); int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket); int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket); +int OnDrop(int id, unsigned char wpnid, unsigned short ammo1, + unsigned short ammo2, unsigned char unknown1, unsigned char unknown2, + unsigned char unknown3, int writesocket); #endif diff --git a/include/structs.h b/include/structs.h index acda92a..6420f69 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,104 +1,113 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, FloooD */ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" #define MAX_CLIENTS 64 #define BUFFER_SIZE 100 struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; short freq; //every freq ms one shoot short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; short special; short team; }; /* * team * 0 - everyone can buy it * 1 - t-only * 2 - ct only * 3 - unbuyable */ struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; short special; }; /* * special * 0 = Normal * 1 = Silencer * 2 = Burst * 3 = Melee * 4 = 1xZoom * 5 = 2xZoom * 6 = Shotgun */ +struct DROPPED_WEAPON +{ + short id, uid; + short ammo1, ammo2; + short x, y; +}; +struct DROPPED_WEAPON **dropped_weapons; +extern int dropped_weapons_count; + struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; int lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; unsigned short deaths; short score; unsigned short x, y; - unsigned short buffer_x[BUFFER_SIZE + 1], buffer_y[BUFFER_SIZE +1]; + unsigned short buffer_x[BUFFER_SIZE + 1], buffer_y[BUFFER_SIZE + 1]; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; unsigned short kills; int reloadtimer, reloading; short dead; int start; unsigned short latency; int firetimer, zoomtimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/src/functions.c b/src/functions.c index 74fb484..aa4ed28 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,561 +1,561 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, FloooD */ #include "../include/functions.h" /** * \fn void UpdateBuffer(void) * \brief update old player locations */ void UpdateBuffer(void) { int id, i; for (id = 1; id < (MAX_CLIENTS); id++) { - for (i = sv_lcbuffer; i >= 1; i--) - { - player[id].buffer_x[i] = player[id].buffer_x[i - 1]; - player[id].buffer_y[i] = player[id].buffer_y[i - 1]; - } - player[id].buffer_x[0] = player[id].x; - player[id].buffer_y[0] = player[id].y; + for (i = sv_lcbuffer; i >= 1; i--) + { + player[id].buffer_x[i] = player[id].buffer_x[i - 1]; + player[id].buffer_y[i] = player[id].buffer_y[i - 1]; + } + player[id].buffer_x[0] = player[id].x; + player[id].buffer_y[0] = player[id].y; } } /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; player[id].zoomtimer = 0; player[id].firetimer = 0; int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } for (i = 0; i <= sv_lcbuffer; i++) { player[id].buffer_x[i] = 0; player[id].buffer_y[i] = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; player[id].slot[i].special = 0; player[id].zoommode = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * */ int PlayerTimeout(int id) { //id = 0; int actualtime = mtime(); - if (((player[id].lastpaket + TIMEOUT*1000) < actualtime) && player[id].lastpaket - != 0) + if (((player[id].lastpaket + TIMEOUT * 1000) < actualtime) + && player[id].lastpaket != 0) { return 1; } return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if (strcmp((char*) sv_password, "")) { serverstatus += 1; } if (sv_usgnonly == 1) { serverstatus += 2; } if (sv_fow == 1) { serverstatus += 4; } if (sv_friendlyfire == 1) { serverstatus += 8; } if (1) //Same Version? { serverstatus += 16; } if (sv_gamemode != 0) { serverstatus += 32; } if (0) //LuaScripts { serverstatus += 64; } if (1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x >> 8) | (*x << 8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x << 24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(unsigned char *message, int id) { /* - unsigned short *pTempNummer = malloc(2); - pTempNummer[0] = message[0]; - pTempNummer[1] = message[1]; - */ - unsigned short *pTempNummer = (unsigned short *)message; + unsigned short *pTempNummer = malloc(2); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + */ + unsigned short *pTempNummer = (unsigned short *) message; if (*pTempNummer % 2 != 0) { if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer + 2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); //free(pTempNummer); return 0; } } if (*pTempNummer - 1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ //free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(unsigned char *message, int id, int writesocket) { - unsigned short *pTempNummer = (unsigned short *)message; + unsigned short *pTempNummer = (unsigned short *) message; /* - unsigned short *pTempNummer = malloc(sizeof(unsigned short)); - pTempNummer[0] = message[0]; - pTempNummer[1] = message[1]; - */ + unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + */ if (*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer + 1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } //free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(unsigned char *password) { if (strcmp((char*) sv_password, (char*) password) != 0) { printf("Password wrong!\n"); return 1; } if (sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length + 1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(int writesocket) * \brief check all player if their reload is ended, * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].reloading != 0) { if (player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if (player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } struct in_addr GetIp(char *name) { struct in_addr ip; struct hostent *dnsresolve; if ((dnsresolve = gethostbyname(name)) == NULL) { printf("Error: Failed to resolve %s!\n", name); ip.s_addr = inet_addr("85.214.102.60"); return ip; //return usgn ip } memcpy(&ip, dnsresolve->h_addr_list[0], dnsresolve->h_length); return ip; } int UsgnRegister(int writesocket) { struct sockaddr_in tempclient; tempclient.sin_family = AF_INET; tempclient.sin_port = htons(36963); tempclient.sin_addr = GetIp("usgn.de"); unsigned char *buffer = malloc(4); if (buffer == NULL) error_exit("Memory error ( UsgnRegister() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 27; position++; buffer[position] = 1; position++; udp_send(writesocket, buffer, 4, &tempclient); free(buffer); printf("[USGN] Sent ADD request to %s...\n", inet_ntoa(tempclient.sin_addr)); return 0; } int UsgnUpdate(int writesocket) { struct sockaddr_in tempclient; tempclient.sin_family = AF_INET; tempclient.sin_port = htons(36963); tempclient.sin_addr = GetIp("usgn.de"); unsigned char *buffer = malloc(4); if (buffer == NULL) error_exit("Memory error ( UsgnRegister() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 28; position++; buffer[position] = 2; position++; udp_send(writesocket, buffer, 4, &tempclient); free(buffer); printf("[USGN] Sent UPDATE request to %s...\n", inet_ntoa(tempclient.sin_addr)); return 0; } void ExecuteFunctionsWithTime(time_t *checktime, int writesocket) { time_t actualtime; time(&actualtime); if (*checktime != actualtime) //prevents executing more times than one in a second { if (actualtime % 5 == 0) //execute every 5 seconds { SendPingList(writesocket); SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status PingAllPlayer(writesocket); } else if (actualtime % 50 == 0) { UsgnUpdate(writesocket); } *checktime = actualtime; } } size_t u_strlen(unsigned char* buffer) { return strlen((char*) buffer); } diff --git a/src/log.c b/src/log.c index fed5343..d1bb2c5 100644 --- a/src/log.c +++ b/src/log.c @@ -1,90 +1,91 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/log.h" /** * \fn void myprintf(char *string, ...) * \brief prints string with time to stdout and logfile * \param *string the string to print out (same syntax as printf) * \param ... the other parameters, if necessary */ void myprintf(char *string, ...) { #ifdef _WIN32 FILE *logfile; time_t rawtime; struct tm * timeinfo; logfile = fopen("log.txt", "a+"); if (logfile != NULL) { time(&rawtime); timeinfo = localtime(&rawtime); - fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, + timeinfo->tm_sec); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string, argzeiger); vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } #else time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); va_end(argzeiger); #endif } /** * \fn void myprintf2(char *string, ...) * \brief same as myprintf, just with the difference, that the time won't be printed * \param *string the string to print out (same syntax as printf) * \param ... the other parameters, if necessary */ void myprintf2(char *string, ...) { #ifdef _WIN32 FILE *logfile; logfile = fopen("log.txt", "a+"); if (logfile != NULL) { va_list argzeiger; va_start(argzeiger,string); vprintf(string, argzeiger); vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } #else va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); va_end(argzeiger); #endif } diff --git a/src/main.c b/src/main.c index 05fd595..d71a6c0 100644 --- a/src/main.c +++ b/src/main.c @@ -1,295 +1,295 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, FloooD */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, sv_hostport); atexit(cleanup); //struct in_addr usgnip = GetIp("usgn.de"); /* FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); */ OnServerStart(); ReadMap(); UsgnRegister(readsocket); /** * \var needed for ExecuteFunctionsWithTime() */ time_t checktime; time(&checktime); int mstime = mtime(); int timecounter = mtime(); int tickcounter = 0; const int fps = 1000 / sv_fps; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; //1ms = 1000 while (1) { if ((timecounter + 1000 - (int) mtime()) <= 0) { fpsnow = (int) tickcounter; tickcounter = 0; timecounter = mtime(); } tickcounter++; UpdateBuffer(); CheckForTimeout(readsocket); ExecuteFunctionsWithTime(&checktime, readsocket); CheckAllPlayerForReload(readsocket); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); select(readsocket + 1, &descriptor, NULL, NULL, &timeout); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation player[id].lastpaket = mtime(); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; + case 24: + rtn = drop(message, tempsize, id, readsocket); + break; case 28: // Spray 28 - 0 - x x - y y - color rtn = spray(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 27: rtn = UsgnPacket(27, message, tempsize, readsocket); break; case 28: rtn = UsgnPacket(28, message, tempsize, readsocket); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } - else - { #ifdef _WIN32 - Sleep(fps + mstime - mtime()); + Sleep(fps + mstime - mtime()); #else - sleep(fps + mstime - mtime()); + sleep(fps + mstime - mtime()); #endif - } mstime = mtime(); } return EXIT_SUCCESS; } diff --git a/src/map.c b/src/map.c index 4410174..4fd9858 100644 --- a/src/map.c +++ b/src/map.c @@ -1,219 +1,220 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/map.h" /** * \fn void ReadMap() * \brief reads the map and put all needed information into a variable * needed: tspawn and ctspawn */ void ReadMap() { FILE *file; int i; tspawncount = 0; ctspawncount = 0; char *mappath = malloc(u_strlen(sv_map) + 5); memcpy(mappath, sv_map, u_strlen(sv_map)); memcpy(mappath + u_strlen(sv_map), ".map\0", 5); file = fopen(mappath, "rb"); if (file == NULL) error_exit("Map not found.. Abort\n"); - else printf("Loading '%s'..", mappath); + else + printf("Loading '%s'..", mappath); free(mappath); //------------------------------ unsigned char *mapheader = ReadLine(file); for (i = 1; i <= 9; i++) ReadByte(file); for (i = 1; i <= 10; i++) ReadInt(file); for (i = 1; i <= 10; i++) ReadLine(file); unsigned char *code = ReadLine(file); unsigned char *tileset = ReadLine(file); unsigned char loaded = ReadByte(file); int maxx = ReadInt(file); int maxy = ReadInt(file); unsigned char *background = ReadLine(file); /*int backgroundx =*/ ReadInt(file); //avoid warnings: unused variable /*int backgroundy =*/ ReadInt(file); /*unsigned char red =*/ ReadByte(file); /*unsigned char green =*/ ReadByte(file); /*unsigned char blue =*/ ReadByte(file); unsigned char *mapcheck = ReadLine(file); //----------------------------------------- unsigned char *tilemode = malloc(loaded + 1); if (tilemode == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= loaded; i++) { tilemode[i] = ReadByte(file); } map = malloc(maxx * sizeof(struct TILE *)); if (map == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= maxx; i++) { map[i] = malloc(maxy * sizeof(struct TILE *)); if (map[i] == NULL) error_exit("Memory error in ReadMap()\n"); int b; for (b = 0; b <= maxy; b++) { unsigned char bytecache = ReadByte(file); if (bytecache > loaded) { bytecache = 0; } map[i][b].tileid = bytecache; map[i][b].mode = tilemode[bytecache]; //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); } } //--------------------------------------- unsigned char enities_count = ReadByte(file); for (i = 0; i <= enities_count - 1; i++) { unsigned char *name = ReadLine(file); unsigned char typ = ReadByte(file); int x = ReadInt(file); int y = ReadInt(file); unsigned char *trigger = ReadLine(file); //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); int b; for (b = 0; b <= 9; b++) { /*int unknownint =*/ReadInt(file); unsigned char *unknown = ReadLine(file); //eprintf("(%d) %s || ", unknownint, unknown); free(unknown); } switch (typ) { case 0: { tspawnx[tspawncount] = x; tspawny[tspawncount] = y; tspawncount++; break; } case 1: { ctspawnx[ctspawncount] = x; ctspawny[ctspawncount] = y; ctspawncount++; break; } default: { break; } } free(name); free(trigger); } fclose(file); eprintf("loaded!\n"); free(mapheader); free(code); free(tileset); free(background); free(mapcheck); } /** * \fn unsigned char *ReadLine(FILE *file) * \brief read from a file stream a cs2d line (ends with \r\n; windows end) * \param *file the file stream * \return a pointer to the read line */ unsigned char *ReadLine(FILE *file) { int position = 0; char *line = NULL; char c; while ((c = fgetc(file)) != 13) { if (c == EOF) error_exit("EndOfFile in ReadByte()\n"); line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = c; position++; } line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = '\0'; position++; fgetc(file); //0x0A return (unsigned char*) line; } /** * \fn unsigned char ReadByte(FILE *file) * \brief read from a file stream a byte * \param *file the file stream * \return the read byte */ unsigned char ReadByte(FILE *file) { unsigned char byte = fgetc(file); if (byte == EOF) error_exit("EndOfFile in ReadByte()\n"); return byte; } /** * \fn int ReadInt(FILE *file) * \brief read from a file stream a integer * \param *file the file stream * \return the read integer */ int ReadInt(FILE *file) { int byte1 = fgetc(file); if (byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); int byte2 = fgetc(file); if (byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); int byte3 = fgetc(file); if (byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); int byte4 = fgetc(file); if (byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/pakets.c b/src/pakets.c index 190779a..03991de 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -77,1710 +77,1749 @@ int connection_setup_known(unsigned char *message, int length, return length; } return paketlength; } /** * \fn int ping_ingame(unsigned char *message, int length, int id, int writesocket) * \brief handles a answer from the server ingame ping. this function calculates the latency * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_ingame(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; if (length < paketlength) { printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; //printf("%s: %d\n", player[id].name, player[id].latency); return paketlength; } /** * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a confirmation for unknown player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } /** * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) * \brief handles a confirmation for known player * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } /** * \fn int fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a fire * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if (length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch (OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } /** * \fn int advanced_fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a advanced_fire (right click) * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int advanced_fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (length < paketlength) { printf("Invalid packet (advanced_fire)!\n"); return length; } unsigned int status = message[1]; switch (OnAdvancedFire(id, status, writesocket)) { case 0: SendAdvancedFireMessage(id, status, writesocket); break; case 1: break; } return paketlength; } /** * \fn int buy(unsigned char *message, int length, int id, int writesocket) * \brief handles a buy request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch (OnBuyAttempt(id, wpnid, writesocket)) { case 0: OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } /** * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) * \brief handles a rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if (length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message + 1, sizeof(float)); if (temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } /** * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) * \brief handles a position walk update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if (length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } /** * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) * \brief handles a position run update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if (length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } /** * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position walk and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if (length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); memcpy(&rotation, message + 5, sizeof(float)); if (rotation >= -180 && rotation <= 180) { switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position run and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if (length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); memcpy(&rotation, message + 5, sizeof(float)); if (rotation >= -180 && rotation <= 180) { switch (OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) * \brief handles a respawn request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if (length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch (OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch (player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp] + 0.5) * 32; player[id].y = (tspawny[tmp] + 0.5) * 32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp] + 0.5) * 32; player[id].y = (ctspawny[tmp] + 0.5) * 32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } /** * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a weapon change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch (OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch (OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if (skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param *client pointer to the client information structure * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if (length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if (tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; - memcpy(tempbuffer + 2, message, paketlength-2); + memcpy(tempbuffer + 2, message, paketlength - 2); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if (length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); if (sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch (message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = u_strlen(sv_name); position++; memcpy(buffer + position, sv_name, u_strlen(sv_name)); position += u_strlen(sv_name); buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if (sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if (length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch (message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS - 1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + u_strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if (paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch (OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength = 4; unsigned char team, unknown; int paketsize; if (paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length - position + 1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( chatmessage() )\n"); memcpy(string, message + position, paketsize); string[paketsize] = '\0'; position += paketsize; switch (OnChatMessage(id, string, team, writesocket)) { case 0: SendChatMessage(id, string, team, writesocket); break; case 1: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch (message[1]) { case 0: { paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if (player[id].joinstatus == 1) { paketlength = 16; // ??? if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; - player[id].name = malloc(stringsize+1); + player[id].name = malloc(stringsize + 1); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message + position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; - unsigned char *password = malloc(stringsize+1); + unsigned char *password = malloc(stringsize + 1); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message + position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; for (i = 0; i <= u_strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; - unsigned char *encryption1 = malloc(stringsize+1); + unsigned char *encryption1 = malloc(stringsize + 1); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message + position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message + position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes /* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif */ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; - player[id].spraylogo = malloc(stringsize+1); + player[id].spraylogo = malloc(stringsize + 1); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message + position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; - unsigned char *maphash = malloc(stringsize+1); + unsigned char *maphash = malloc(stringsize + 1); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; - player[id].win = malloc(stringsize+1); + player[id].win = malloc(stringsize + 1); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message + position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch (tempstatus) { case 0x00: stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); position += u_strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } //stringsize = 16 + u_strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if (stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if (player[id].joinstatus == 2) { int position = 2; paketlength = 5; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } position++; - unsigned char *maphash = malloc(stringsize+1); + unsigned char *maphash = malloc(stringsize + 1); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMaphash: %s\n", maphash); //pre_authcode_respond stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("pre_authcon_respond too big\n"); return length; } position++; - unsigned char *pre_authcode_respond = malloc(stringsize+1); + unsigned char *pre_authcode_respond = malloc(stringsize + 1); if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(pre_authcode_respond, message + position, stringsize); pre_authcode_respond[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); //Player Version //unsigned char mapstatus = message[position]; //avoid warning position++; //printf("\tMapstatus: %d\n", mapstatus); free(pre_authcode_respond); free(maphash); //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if (player[id].joinstatus == 3) { int position = 2; paketlength = 3; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Mapname too big\n"); return length; } position++; - unsigned char *mapname = malloc(stringsize+1); + unsigned char *mapname = malloc(stringsize + 1); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message + position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(sv_name); position++; memcpy(buffer + position, sv_name, u_strlen(sv_name)); position += u_strlen(sv_name); buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_friendlyfire; position++; buffer[position] = 0; //Unknown position++; buffer[position] = mp_roundtime; position++; buffer[position] = mp_freezetime; position++; buffer[position] = mp_c4timer; position++; buffer[position] = 32; //Unknown position++; buffer[position] = 124; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 1; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_maxplayers; position++; buffer[position] = sv_fow; position++; buffer[position] = mp_specmode; position++; buffer[position] = sv_gamemode; position++; buffer[position] = mp_respawndelay; position++; buffer[position] = mp_infammo; position++; buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; position++; buffer[position] = onlineplayer; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 1 && i != id) { unsigned char *encodedname; encodedname = GetEncodedString(player[i].name, u_strlen( player[i].name)); unsigned short *deaths = &player[i].deaths; unsigned short tempscore = (unsigned) (player[i].deaths + 1000); unsigned short *score = &tempscore; unsigned short tempx = (player[i].x); unsigned short tempy = (player[i].y); unsigned short *x = &tempx; unsigned short *y = &tempy; float *ptemprotation = &player[i].rotation; int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = i; position++; buffer[position] = u_strlen(encodedname); position++; memcpy(buffer + position, encodedname, u_strlen(encodedname)); position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[i].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; /* buffer[position] = score[0]; //Deaths position++; buffer[position] = score[1]; //Deaths position++; */ memcpy(buffer + position, score, 2); position += 2; /* buffer[position] = deaths[0]; //Deaths position++; buffer[position] = deaths[1]; //Deaths position++; */ memcpy(buffer + position, deaths, 2); position += 2; memcpy(buffer + position, x, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; memcpy(buffer + position, y, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = ptemprotation[0]; //Rotation position++; buffer[position] = ptemprotation[1]; //Rotation position++; buffer[position] = player[i].health; //Health position++; buffer[position] = player[i].armor; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe position++; buffer[position] = 0; //Unknown position++; /* 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 e8 03 00 00 12 01 00 00 01 03 e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 */ } } if (1) { unsigned char *encodedname; encodedname = GetEncodedString(player[id].name, u_strlen( player[id].name)); int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = id; position++; buffer[position] = u_strlen(encodedname); position++; memcpy(buffer + position, encodedname, u_strlen(encodedname)); position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[id].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 232; //Unknown position++; buffer[position] = 3; //Unknown position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //X position++; buffer[position] = 0; //X position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Health position++; buffer[position] = 0; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Aktuelle Waffe 50 = Knife position++; buffer[position] = 0; //Unknown position++; } SendToPlayer(buffer, position, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- HostageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 2; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ItemData ----------- /* fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 */ stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 3; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- EnityData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 4; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 5; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ProjectileData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 6; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectImageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 7; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- Final ACK ----------- stringsize = 7; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 200; //third payload position++; buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); player[id].joinstatus = 4; free(mapname); OnJoin(id, writesocket); } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } default: { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } return paketlength; } int leave(int id, int writesocket) { OnLeave(id, writesocket); free(player[id].name); free(player[id].usgn); free(player[id].spraylogo); free(player[id].win); player[id].name = NULL; player[id].usgn = NULL; player[id].spraylogo = NULL; player[id].win = NULL; onlineplayer--; ClearPlayer(id); return 2; } int reload(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int status; status = message[position]; position++; if (status == 1) { SendReloadMessage(id, 1, writesocket); player[id].reloading = player[id].actualweapon; player[id].reloadtimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].reloadtime; } return paketlength; } int spray(unsigned char *message, int length, int id, int writesocket) { // 28 0 xx yy c // 0 1 23 45 6 struct { unsigned char hi; unsigned char lo; } x, y; if (length < 7) { printf("Invalid packet (spray)!\n"); return length; } x.lo = message[2]; x.hi = message[3]; y.lo = message[4]; y.hi = message[5]; unsigned short xx = x.hi * 256 + x.lo, yy = y.hi * 256 + y.lo; unsigned char c = message[6]; unsigned char i = (char) id; // Postprocessing if needed, then send back exact same data // xx and yy are positions, not tiles. SendSprayMessage(i, xx, yy, c, writesocket); return 7; } int UsgnPacket(int packetid, unsigned char *message, int length, int writesocket) //No check if really from usgn.de { int paketlength = 2; switch (packetid) { case 27: if (message[1] == 1) { printf("[USGN] Server successfully added to the serverlist..\n"); } else { printf("[USGN] Server NOT added to the serverlist.. (Code: %d)\n", message[3]); } paketlength = 2; break; case 28: if (message[1] == 2) { printf("[USGN] Server successfully updated in the serverlist..\n"); } else { printf("[USGN] Server NOT updated in the serverlist.. (Code: %d)\n", message[3]); } paketlength = 2; break; default: printf("[USGN] Unknown Message recieved: "); int i; for (i = 0; i < length; i++) { eprintf("%d-", message[i]); } eprintf("\n"); paketlength = length; break; } return paketlength; } + +int drop(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 7; + if (length < paketlength) + { + printf("Invalid packet (drop)!\n"); + return length; + } + + int position = 1; + unsigned char wpnid, unknown1, unknown2, unknown3; + unsigned short ammo1, ammo2; + + wpnid = message[position]; + position++; + ammo1 = message[position]; + position++; + unknown1 = message[position]; + position++; + ammo2 = message[position]; + position++; + unknown2 = message[position]; + position++; + unknown3 = message[position]; + position++; + + switch (OnDrop(id, wpnid, ammo1, ammo2, unknown1, unknown2, unknown3, writesocket)) + { + case 0: + RemovePlayerWeapon(id, wpnid); + SendDropMessage(id, wpnid, ammo1, ammo2, unknown1, unknown2, unknown3, writesocket); + break; + default: + break; + } + + return paketlength; +} diff --git a/src/respond_messages.c b/src/respond_messages.c index 14f8bed..d7ba21b 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -229,512 +229,590 @@ void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if (status == 0) buffer[position] = 14; else if (status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; memcpy(buffer + position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer + position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch (status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch (status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + u_strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = u_strlen(player[id].name); position++; memcpy(buffer + position, player[id].name, u_strlen(player[id].name)); position += u_strlen(player[id].name); buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if (player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + u_strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = u_strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, u_strlen(message)); position += u_strlen(message); if (team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if (team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } // 28 - id - xx - yy - c void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket) { int stringsize = 8; unsigned char *buffer = malloc(stringsize * sizeof(char)); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position++] = 28; buffer[position++] = 0; buffer[position++] = id; memcpy(buffer + position, &xx, 2); position += 2; memcpy(buffer + position, &yy, 2); position += 2; buffer[position++] = c; // SendToAll(buffer, stringsize, 1, writesocket); -- Make sure that the spray-image send packet is crafted first. free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int victim, int writesocket) { char sHealth[4]; char sArmor[4]; //= player[id].health int sHealthLength = sprintf(sHealth, "%i", (int) player[id].health); int sArmorLength = sprintf(sArmor, "%i", (int) player[id].armor); int sNameLength = u_strlen(player[id].name); int length = 4 + sNameLength + sHealthLength + sArmorLength; // 4 for a6 spaces int stringsize = 17 + length; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); int position = 0; buffer[position] = 19; position++; buffer[position] = victim; position++; buffer[position] = id; position++; buffer[position] = player[id].slot[player[id].actualweapon].id; position++; memcpy(buffer + position, &player[victim].x, 2); position += 2; memcpy(buffer + position, &player[victim].y, 2); position += 2; unsigned short unknown1 = 240; memcpy(buffer + position, &unknown1, 2); position += 2; buffer[position] = 1; position++; memcpy(buffer + position, &length, 2); position += 2; buffer[position] = 'k'; position++; buffer[position] = 166; //166 acts like string seperator position++; memcpy(buffer + position, player[id].name, sNameLength); position += sNameLength; buffer[position] = 166; position++; memcpy(buffer + position, &sHealth, sHealthLength); position += sHealthLength; buffer[position] = 166; position++; memcpy(buffer + position, &sArmor, sArmorLength); position += sArmorLength; SendToPlayer(buffer, stringsize, victim, 1, writesocket); free(buffer); stringsize = 8; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); position = 0; buffer[position] = 19; position++; buffer[position] = victim; position++; buffer[position] = id; position++; buffer[position] = player[id].slot[player[id].actualweapon].id; position++; memcpy(buffer + position, &player[victim].x, 2); position += 2; memcpy(buffer + position, &player[victim].y, 2); position += 2; SendToAllOther(victim, buffer, stringsize, 1, writesocket); free(buffer); } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count * 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer + position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); } void SendBuyFailedMessage(int id, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyFailedMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = status; position++; buffer[position] = 44; position++; buffer[position] = 1; position++; buffer[position] = 0; position++; //TODO what does the last lines mean? /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone * */ SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); } + +void SendDropMessage(int id, int wpnid, int ammo1, int ammo2, int unknown1, + int unknown2, int unknown3, int writesocket) +{ + /* + int stringsize = 7; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendDropMessage() )\n"); + + int position = 0; + buffer[position] = 24; + position++; + buffer[position] = wpnid; + position++; + buffer[position] = (unsigned char) ammo1; + position++; + buffer[position] = 0; + position++; + buffer[position] = (unsigned char) ammo2; + position++; + buffer[position] = 0; + position++; + buffer[position] = 0; + position++; + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + buffer = NULL; + */ + + int stringsize = 19; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendDropMessage() )\n"); + unsigned short tilex = (unsigned short) player[id].x / 32; + unsigned short tiley = (unsigned short) player[id].y / 32; + + int position = 0; + + buffer[position] = 24; + position++; + buffer[position] = id; + position++; + buffer[position] = wpnid; + position++; + buffer[position] = (unsigned char) ammo1; + position++; + buffer[position] = unknown1; + position++; + buffer[position] = (unsigned char) ammo2; + position++; + buffer[position] = unknown2; + position++; + memcpy(buffer + position, &tilex, 2); + position += 2; + memcpy(buffer + position, &tiley, 2); + position += 2; + buffer[position] = 0; + position++; + buffer[position] = 0; + position++; + buffer[position] = 0; + position++; + buffer[position] = 1; + position++; + buffer[position] = 0; + position++; + buffer[position] = 0; + position++; + buffer[position] = 0; + position++; + buffer[position] = 50; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} diff --git a/src/script-functions.c b/src/script-functions.c index fe0c8fb..f797558 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,581 +1,609 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, FloooD */ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("Listening at port %d and using name '%s'\n", sv_hostport, sv_name); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) { - if(player[id].money + mp_dmspawnmoney > 65000) player[id].money = 65000; - else player[id].money += mp_dmspawnmoney; + if (player[id].money + mp_dmspawnmoney > 65000) + player[id].money = 65000; + else + player[id].money += mp_dmspawnmoney; return 0; } else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; //printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; int temptime = mtime(); if (temptime < player[id].zoomtimer) { printf("Zoomtimer error!\n"); return 1; } else { player[id].zoomtimer = mtime() + 500; } switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); return 1; case 1: case 2: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; break; } case 4: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 5: { if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; break; } else if (player[id].zoommode == 2) { player[id].zoommode = 0; break; } return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); return 1; } } return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } int temptime = mtime(); if (temptime < player[id].firetimer) { printf("Firetimer error!\n"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; } int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; int frames = fpsnow * player[id].latency / 1000; if (frames > sv_lcbuffer) { frames = sv_lcbuffer; } float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { - if (sqrt((player[b].buffer_x[frames] - startx)*(player[b].buffer_x[frames] - startx) - + (player[b].buffer_y[frames] - starty)*(player[b].buffer_y[frames] - starty)) - <= 16) + if (sqrt((player[b].buffer_x[frames] - startx) + * (player[b].buffer_x[frames] - startx) + + (player[b].buffer_y[frames] - starty) + * (player[b].buffer_y[frames] - starty)) <= 16) /*if (sqrt((player[b].x - startx) * (player[b].x - startx) - + (player[b].y - starty) * (player[b].y - starty)) - <= 16)*/ + + (player[b].y - starty) * (player[b].y - starty)) + <= 16)*/ { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); //printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].name != NULL) //test if weapon available { if (player[id].money - weapons[wpnid].price >= 0) { if (weapons[wpnid].team == 0 || weapons[wpnid].team == player[id].team) //Check if he is in the right team to buy this weapon { if (player[id].team == 1) { //Check if in buyzone int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { if (player[id].slot[g].id != wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { if (player[id].slot[g].id != wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } SendBuyFailedMessage(id, 255, writesocket); //Not in a buyzone return 1; } } else { SendBuyFailedMessage(id, 252, writesocket); //you cant buy this item return 1; } } else { SendBuyFailedMessage(id, 253, writesocket); //not enough money return 1; } } } //if nothing found SendBuyFailedMessage(id, 244, writesocket); /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone */ return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; if (player[hitter].money + 300 > 65000) player[hitter].money = 65000; else player[hitter].money += 300; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); SendKillMessage(hitter, victim, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK 1 - don't send it */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (u_strlen(message) >= 4 && strncmp((char *) message, "!log", 4) == 0) { char* log = malloc(u_strlen(message) - 5 + 1); //+1 for '\0' if (log == NULL) error_exit("Memory error ( OnChatMessage() -> log )\n"); strncpy(log, (char *) message + 5, u_strlen(message) - 5); log[u_strlen(message) - 5] = '\0'; eprintf("[LOG]: %s\n",log); free(log); return 1; } else if (u_strlen(message) >= 4 && strncmp((char *) message, "!fps", 4) == 0) { char buffer[30]; //Resulting stringlength unknown: Text = 24 chars sprintf(buffer, "Actually server FPS: %d", fpsnow); SendMessageToPlayer(id, buffer, 1, writesocket); return 1; } if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } + +/* + int OnDrop(int id, unsigned char wpnid, unsigned short ammo1, unsigned short ammo2, unsigned char unknown1, int writesocket) + Return Values: + 0 - OK + 1 - Don't drop + */ +int OnDrop(int id, unsigned char wpnid, unsigned short ammo1, unsigned short ammo2, + unsigned char unknown1, unsigned char unknown2, unsigned char unknown3, int writesocket) +{ + int i; + for (i = 0; i < 10; i++) + { + if (player[id].slot[i].id == wpnid) + { + if (player[id].slot[i].ammo1 == ammo1 && player[id].slot[i].ammo2 + == ammo2) + { + return 0; + } + break; + } + } + return 1; +} diff --git a/src/settings.c b/src/settings.c index c0de0cf..3739647 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,179 +1,184 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, GuccaGucca, FloooD */ #include "../include/settings.h" -unsigned char pre_authcode[] = "5TWs3Obv7"; -char startweapons[] = {50}; +unsigned char pre_authcode[] = "5TWs3Obv7"; +char startweapons[] = +{ 50 }; int fpsnow = 0; - -unsigned char *sv_name = NULL; -unsigned char *sv_map = NULL; -unsigned int sv_hostport = 0; -unsigned short sv_maxplayers = 0; -unsigned short sv_fps = 0; -unsigned short sv_lcbuffer = 0; -unsigned short sv_fow = 0; -unsigned short sv_gamemode = 0; -unsigned short sv_friendlyfire = 0; -unsigned short sv_usgnonly = 0; -unsigned char *sv_password = 0; -unsigned short bot_count = 0; - -unsigned short mp_roundtime = 0; -unsigned short mp_freezetime = 0; -unsigned short mp_c4timer = 0; -unsigned short mp_infammo = 0; -unsigned short mp_respawndelay = 0; -unsigned short mp_specmode = 0; -unsigned short onlineplayer = 0; -unsigned short mp_startmoney = 0; -unsigned short mp_dmspawnmoney = 0; - - +int dropped_weapons_count = 0; + +unsigned char *sv_name = NULL; +unsigned char *sv_map = NULL; +unsigned int sv_hostport = 0; +unsigned short sv_maxplayers = 0; +unsigned short sv_fps = 0; +unsigned short sv_lcbuffer = 0; +unsigned short sv_fow = 0; +unsigned short sv_gamemode = 0; +unsigned short sv_friendlyfire = 0; +unsigned short sv_usgnonly = 0; +unsigned char *sv_password = 0; +unsigned short bot_count = 0; + +unsigned short mp_roundtime = 0; +unsigned short mp_freezetime = 0; +unsigned short mp_c4timer = 0; +unsigned short mp_infammo = 0; +unsigned short mp_respawndelay = 0; +unsigned short mp_specmode = 0; +unsigned short onlineplayer = 0; +unsigned short mp_startmoney = 0; +unsigned short mp_dmspawnmoney = 0; struct setting { - char *name; - char *value; + char *name; + char *value; }; int tointeger(char * c); double todouble(char *c); struct setting * settings[256]; int entries; int readConfig() { - FILE * pFile; - char s[256]; - int setting_num = 0; - pFile = fopen("server.cfg","r"); - - if(pFile == NULL) perror("Error opening file: server.cfg"); - else - { - while((fgets(s,sizeof(s),pFile))!= NULL) - { - if(s[0]=='\n' || (s[0] == '/' && s[1] == '/')) - continue; - //char *s1,*s2,*type; - - int i; - for(i = 0; i < strlen(s);i++) - { - if(s[i] == ' ') - { - i++; //skip ' ' char - struct setting * var; - var = (struct setting*)malloc(sizeof(struct setting)); - - var->name = malloc(i+1); - if(var->name == NULL) error_exit("Memory error in readConfig()\n"); - strncpy(var->name,s,i); - var->name[i] = '\0'; - if(s[strlen(s)-i-1] == '\n') //if \n found then remove it - { - var->value = malloc(strlen(s)-i-1 +1); - if(var->value == NULL) error_exit("Memory error in readConfig()\n"); - strncpy(var->value,&s[i],strlen(s)-i-1); //also ommit the \n - var->value[strlen(s)-i-1] = '\0'; - } - else - { - var->value = malloc(strlen(s)-i +1); - if(var->value == NULL) error_exit("Memory error in readConfig()\n"); - strncpy(var->value,&s[i],strlen(s)-i); //also ommit the \n - var->value[strlen(s)-i] = '\0'; - } - - - settings[setting_num] = var; - break; - } - } - setting_num++; - } - fclose(pFile); - } - return setting_num; + FILE * pFile; + char s[256]; + int setting_num = 0; + pFile = fopen("server.cfg", "r"); + + if (pFile == NULL) + perror("Error opening file: server.cfg"); + else + { + while ((fgets(s, sizeof(s), pFile)) != NULL) + { + if (s[0] == '\n' || (s[0] == '/' && s[1] == '/')) + continue; + //char *s1,*s2,*type; + + int i; + for (i = 0; i < strlen(s); i++) + { + if (s[i] == ' ') + { + i++; //skip ' ' char + struct setting * var; + var = (struct setting*) malloc(sizeof(struct setting)); + + var->name = malloc(i + 1); + if (var->name == NULL) + error_exit("Memory error in readConfig()\n"); + strncpy(var->name, s, i); + var->name[i] = '\0'; + if (s[strlen(s) - i - 1] == '\n') //if \n found then remove it + { + var->value = malloc(strlen(s) - i - 1 + 1); + if (var->value == NULL) + error_exit("Memory error in readConfig()\n"); + strncpy(var->value, &s[i], strlen(s) - i - 1); //also ommit the \n + var->value[strlen(s) - i - 1] = '\0'; + } + else + { + var->value = malloc(strlen(s) - i + 1); + if (var->value == NULL) + error_exit("Memory error in readConfig()\n"); + strncpy(var->value, &s[i], strlen(s) - i); //also ommit the \n + var->value[strlen(s) - i] = '\0'; + } + + settings[setting_num] = var; + break; + } + } + setting_num++; + } + fclose(pFile); + } + return setting_num; } char *GetValue(char *sname, char *alternate)////struct setting ** arr , int length) { - int i; - for(i = 0; i < entries; i++) - { - if(settings[i] != NULL) - { - struct setting *var = settings[i]; - if(strcmp(var->name,sname)==0) - { - char *string = malloc(strlen(var->value)+1); - if(string == NULL) error_exit("Memory error in GetValue()\n"); - strncpy(string, var->value, strlen(var->value)); - string[strlen(var->value)] = '\0'; - - free(var->name); - free(var->value); - free(var); //also frees settings[i] - settings[i] = NULL; - return string; - } - } - - } - //If not found - char *string = malloc(strlen(alternate)+1); - if(string == NULL) error_exit("Memory error in GetValue()\n"); - strncpy(string, alternate, strlen(alternate)); - string[strlen(alternate)] = '\0'; - - return string; // doesn't exist + int i; + for (i = 0; i < entries; i++) + { + if (settings[i] != NULL) + { + struct setting *var = settings[i]; + if (strcmp(var->name, sname) == 0) + { + char *string = malloc(strlen(var->value) + 1); + if (string == NULL) + error_exit("Memory error in GetValue()\n"); + strncpy(string, var->value, strlen(var->value)); + string[strlen(var->value)] = '\0'; + + free(var->name); + free(var->value); + free(var); //also frees settings[i] + settings[i] = NULL; + return string; + } + } + + } + //If not found + char *string = malloc(strlen(alternate) + 1); + if (string == NULL) + error_exit("Memory error in GetValue()\n"); + strncpy(string, alternate, strlen(alternate)); + string[strlen(alternate)] = '\0'; + + return string; // doesn't exist } void ReadCfg() { - entries = readConfig(); - - sv_name = (unsigned char *)GetValue("sv_name", "Alpha Custom CS2D Server"); - sv_map = (unsigned char *)GetValue("sv_map", "de_cs2d"); - sv_hostport = tointeger(GetValue("sv_hostport", "36963")); - sv_maxplayers = tointeger(GetValue("sv_maxplayers", "32")) +1; - sv_fps = tointeger(GetValue("sv_fps", "250")); - sv_lcbuffer = tointeger(GetValue("sv_lcbuffer", "100")); - sv_fow = tointeger(GetValue("sv_fow", "0")); - sv_gamemode = tointeger(GetValue("sv_gamemode", "2")); - sv_friendlyfire = tointeger(GetValue("sv_friendlyfire", "0")); - sv_usgnonly = tointeger(GetValue("sv_usgnonly", "0")); - sv_password = (unsigned char *)GetValue("sv_password", ""); - bot_count = tointeger(GetValue("bot_count", "0")); - - mp_roundtime = tointeger(GetValue("mp_roundtime", "5")); - mp_freezetime = tointeger(GetValue("mp_freezetime", "0")); - mp_c4timer = tointeger(GetValue("mp_c4timer", "35")); - mp_infammo = tointeger(GetValue("mp_infammo", "0")); - mp_respawndelay = tointeger(GetValue("mp_respawndelay", "0")); - mp_specmode = tointeger(GetValue("mp_specmode", "0")); - mp_startmoney = tointeger(GetValue("mp_startmoney", "1000")); - mp_dmspawnmoney = tointeger(GetValue("mp_dmspawnmoney", "32000")); + entries = readConfig(); + + sv_name = (unsigned char *) GetValue("sv_name", "Alpha Custom CS2D Server"); + sv_map = (unsigned char *) GetValue("sv_map", "de_cs2d"); + sv_hostport = tointeger(GetValue("sv_hostport", "36963")); + sv_maxplayers = tointeger(GetValue("sv_maxplayers", "32")) + 1; + sv_fps = tointeger(GetValue("sv_fps", "250")); + sv_lcbuffer = tointeger(GetValue("sv_lcbuffer", "100")); + sv_fow = tointeger(GetValue("sv_fow", "0")); + sv_gamemode = tointeger(GetValue("sv_gamemode", "2")); + sv_friendlyfire = tointeger(GetValue("sv_friendlyfire", "0")); + sv_usgnonly = tointeger(GetValue("sv_usgnonly", "0")); + sv_password = (unsigned char *) GetValue("sv_password", ""); + bot_count = tointeger(GetValue("bot_count", "0")); + + mp_roundtime = tointeger(GetValue("mp_roundtime", "5")); + mp_freezetime = tointeger(GetValue("mp_freezetime", "0")); + mp_c4timer = tointeger(GetValue("mp_c4timer", "35")); + mp_infammo = tointeger(GetValue("mp_infammo", "0")); + mp_respawndelay = tointeger(GetValue("mp_respawndelay", "0")); + mp_specmode = tointeger(GetValue("mp_specmode", "0")); + mp_startmoney = tointeger(GetValue("mp_startmoney", "1000")); + mp_dmspawnmoney = tointeger(GetValue("mp_dmspawnmoney", "32000")); } int tointeger(char *c) { int buff = atoi(c); free(c); return buff; } double todouble(char *c) { double buff = atof(c); free(c); return buff; } diff --git a/src/weapons.c b/src/weapons.c index 222ae25..aaa9000 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,65 +1,67 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/weapons.h" void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime, short special, short team) { if (name != NULL) { weapons[id].name = malloc(strlen(name) + 1); if (weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); strncpy(weapons[id].name, name, strlen(name) + 1); } else { weapons[id].name = NULL; } - weapons[id].weapondamage = wpndmg; - weapons[id].weapondamage_z1 = wpndmg_z1; - weapons[id].weapondamage_z2 = wpndmg_z2; - if(freq != 0) - weapons[id].freq = (short)(1/freq)*60*1000; - else - weapons[id].freq = 1000; - weapons[id].speed = speed; - weapons[id].slot = slot; - weapons[id].price = price; - weapons[id].range = range; - weapons[id].accuracy = accuracy; - weapons[id].ammo1 = ammo1; - weapons[id].ammo2 = ammo2; - weapons[id].reloadtime = reloadtime; - weapons[id].special = special; - weapons[id].team = team; + weapons[id].weapondamage = wpndmg; + weapons[id].weapondamage_z1 = wpndmg_z1; + weapons[id].weapondamage_z2 = wpndmg_z2; + if (freq != 0) + weapons[id].freq = (short) (1 / freq) * 60 * 1000; + else + weapons[id].freq = 1000; + weapons[id].speed = speed; + weapons[id].slot = slot; + weapons[id].price = price; + weapons[id].range = range; + weapons[id].accuracy = accuracy; + weapons[id].ammo1 = ammo1; + weapons[id].ammo2 = ammo2; + weapons[id].reloadtime = reloadtime; + weapons[id].special = special; + weapons[id].team = team; } void WeaponInit() { int i; - for(i = 0; i <= 99; i++) + for (i = 0; i <= 99; i++) { - AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0); + AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } - AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000, 1, 0); - AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000, 2, 0); - AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000, 0, 0); - AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000, 0, 0); - AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000, 0, 0); - AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000, 0, 0); - AddWeapon(20,"MP5" , 13 , 0, 0, 500 , 1, 1,1500, 300, 2 , 30, 120, 1000, 0, 0); - AddWeapon(21,"TMP" , 9 , 0, 0, 750 , 1, 1,1250, 100, 4 , 30, 120, 1000, 0, 2); - AddWeapon(22,"P90" , 11 , 0, 0, 750 , 1, 1,2350, 300, 3 , 50, 100, 1000, 0, 2); - AddWeapon(35, "AWP" , 50 , 65 , 150, 23 , 3, 1, 4750 , 400, 0 , 10, 30, 2000, 5, 0); - AddWeapon(50, "Knife", 50, 100, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0, 3, 0); + AddWeapon(1, "USP", 24, 0, 0, 166, 1, 2, 500, 300, 0, 12, 100, 1000, 1, 0); + AddWeapon(2, "Glock", 21, 0, 0, 166, 1, 2, 400, 250, 0, 20, 120, 1000, 2, 0); + AddWeapon(3, "Deagle", 34, 0, 0, 100, 1, 2, 550, 300, 0, 7, 35, 1000, 0, 0); + AddWeapon(4, "P228", 22, 0, 0, 166, 1, 2, 600, 300, 0, 13, 35, 1000, 0, 0); + AddWeapon(5, "Elite", 22, 0, 0, 187, 1, 2, 1000, 300, 0, 13, 120, 1000, 0, + 0); + AddWeapon(6, "Five-Seven", 21, 0, 0, 187, 1, 2, 750, 300, 0, 20, 100, 2000, + 0, 0); + AddWeapon(20, "MP5", 13, 0, 0, 500, 1, 1, 1500, 300, 2, 30, 120, 1000, 0, 0); + AddWeapon(21, "TMP", 9, 0, 0, 750, 1, 1, 1250, 100, 4, 30, 120, 1000, 0, 2); + AddWeapon(22, "P90", 11, 0, 0, 750, 1, 1, 2350, 300, 3, 50, 100, 1000, 0, 2); + AddWeapon(35, "AWP", 50, 65, 150, 23, 3, 1, 4750, 400, 0, 10, 30, 2000, 5, + 0); + AddWeapon(50, "Knife", 50, 100, 0, 1, 1, 2, 0, 8, 0, -1, -1, 0, 3, 0); } -
Jermuk/custom_cs2dsrv
f5d245b2a4af647356edc9d3e968790f49f11a6f
Added FlooD's lag compensation repository
diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe new file mode 100644 index 0000000..d9325ce Binary files /dev/null and b/Release/custom_cs2dsrv.exe differ diff --git a/include/functions.h b/include/functions.h index 6ab13f9..371538f 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,35 +1,36 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" +void UpdateBuffer(void); int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(int writesocket); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(unsigned char *message, int id); void PaketConfirmation(unsigned char *message, int id, int writesocket); int CheckPlayerData(unsigned char *password); unsigned char *GetEncodedString(unsigned char *string, int length); void CheckAllPlayerForReload(int writesocket); struct in_addr GetIp(char *name); int UsgnRegister(int writesocket); int UsgnUpdate(int writesocket); void ExecuteFunctionsWithTime(time_t *checktime, int writesocket); size_t u_strlen(unsigned char* buffer); #endif // FUNCTIONS_H_INCLUDED diff --git a/include/settings.h b/include/settings.h index 11c8225..580f8cb 100644 --- a/include/settings.h +++ b/include/settings.h @@ -1,52 +1,53 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, GuccaGucca */ #ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #include "../include/main.h" #define MAX_BUF 1024 /* --- Server Settings --- */ -#define LOCAL_PORT 1994 #define MAX_CLIENTS 64 #define TIMEOUT 10 #define SETTINGS_PATH "server.cfg" -#define FPS 1000 //max allowed is 1000 extern unsigned char pre_authcode[]; extern unsigned char *sv_name; extern unsigned char *sv_map; extern unsigned int sv_hostport; +extern unsigned short sv_fps; +extern unsigned short sv_lcbuffer; extern unsigned short sv_maxplayers; extern unsigned short sv_fow; extern unsigned short sv_gamemode; extern unsigned short sv_friendlyfire; extern unsigned short sv_usgnonly; extern unsigned char *sv_password; extern unsigned short bot_count; extern unsigned short mp_roundtime; extern unsigned short mp_freezetime; extern unsigned short mp_c4timer; extern unsigned short mp_infammo; extern unsigned short mp_respawndelay; extern unsigned short mp_specmode; extern unsigned short onlineplayer; extern unsigned short mp_startmoney; +extern unsigned short mp_dmspawnmoney; extern int fpsnow; #define STARTWEAPONS_COUNT 1 extern char startweapons[]; void ReadCfg(); #endif // SETTINGS_H_INCLUDED diff --git a/include/structs.h b/include/structs.h index f2c6ffa..acda92a 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,102 +1,104 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * - * Author/s of this file: Jermuk + * Author/s of this file: Jermuk, FloooD */ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" #define MAX_CLIENTS 64 +#define BUFFER_SIZE 100 struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; short freq; //every freq ms one shoot short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; short special; short team; }; /* * team * 0 - everyone can buy it * 1 - t-only * 2 - ct only * 3 - unbuyable */ struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; short special; }; /* * special * 0 = Normal * 1 = Silencer * 2 = Burst * 3 = Melee * 4 = 1xZoom * 5 = 2xZoom * 6 = Shotgun */ struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; int lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; unsigned short deaths; short score; unsigned short x, y; + unsigned short buffer_x[BUFFER_SIZE + 1], buffer_y[BUFFER_SIZE +1]; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; unsigned short kills; int reloadtimer, reloading; short dead; int start; unsigned short latency; int firetimer, zoomtimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/src/functions.c b/src/functions.c index a50cdb9..74fb484 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,537 +1,561 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * - * Author/s of this file: Jermuk + * Author/s of this file: Jermuk, FloooD */ #include "../include/functions.h" +/** + * \fn void UpdateBuffer(void) + * \brief update old player locations + */ +void UpdateBuffer(void) +{ + int id, i; + for (id = 1; id < (MAX_CLIENTS); id++) + { + for (i = sv_lcbuffer; i >= 1; i--) + { + player[id].buffer_x[i] = player[id].buffer_x[i - 1]; + player[id].buffer_y[i] = player[id].buffer_y[i - 1]; + } + player[id].buffer_x[0] = player[id].x; + player[id].buffer_y[0] = player[id].y; + } +} + /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; player[id].zoomtimer = 0; player[id].firetimer = 0; int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } + for (i = 0; i <= sv_lcbuffer; i++) + { + player[id].buffer_x[i] = 0; + player[id].buffer_y[i] = 0; + } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; player[id].slot[i].special = 0; player[id].zoommode = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * */ int PlayerTimeout(int id) { //id = 0; int actualtime = mtime(); if (((player[id].lastpaket + TIMEOUT*1000) < actualtime) && player[id].lastpaket != 0) { return 1; } return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if (strcmp((char*) sv_password, "")) { serverstatus += 1; } if (sv_usgnonly == 1) { serverstatus += 2; } if (sv_fow == 1) { serverstatus += 4; } if (sv_friendlyfire == 1) { serverstatus += 8; } if (1) //Same Version? { serverstatus += 16; } if (sv_gamemode != 0) { serverstatus += 32; } if (0) //LuaScripts { serverstatus += 64; } if (1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x >> 8) | (*x << 8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x << 24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(unsigned char *message, int id) { /* unsigned short *pTempNummer = malloc(2); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; */ unsigned short *pTempNummer = (unsigned short *)message; if (*pTempNummer % 2 != 0) { if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer + 2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); //free(pTempNummer); return 0; } } if (*pTempNummer - 1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ //free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(unsigned char *message, int id, int writesocket) { unsigned short *pTempNummer = (unsigned short *)message; /* unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; */ if (*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer + 1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } //free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(unsigned char *password) { if (strcmp((char*) sv_password, (char*) password) != 0) { printf("Password wrong!\n"); return 1; } if (sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length + 1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(int writesocket) * \brief check all player if their reload is ended, * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].reloading != 0) { if (player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if (player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } struct in_addr GetIp(char *name) { struct in_addr ip; struct hostent *dnsresolve; if ((dnsresolve = gethostbyname(name)) == NULL) { printf("Error: Failed to resolve %s!\n", name); ip.s_addr = inet_addr("85.214.102.60"); return ip; //return usgn ip } memcpy(&ip, dnsresolve->h_addr_list[0], dnsresolve->h_length); return ip; } int UsgnRegister(int writesocket) { struct sockaddr_in tempclient; tempclient.sin_family = AF_INET; tempclient.sin_port = htons(36963); tempclient.sin_addr = GetIp("usgn.de"); unsigned char *buffer = malloc(4); if (buffer == NULL) error_exit("Memory error ( UsgnRegister() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 27; position++; buffer[position] = 1; position++; udp_send(writesocket, buffer, 4, &tempclient); free(buffer); printf("[USGN] Sent ADD request to %s...\n", inet_ntoa(tempclient.sin_addr)); return 0; } int UsgnUpdate(int writesocket) { struct sockaddr_in tempclient; tempclient.sin_family = AF_INET; tempclient.sin_port = htons(36963); tempclient.sin_addr = GetIp("usgn.de"); unsigned char *buffer = malloc(4); if (buffer == NULL) error_exit("Memory error ( UsgnRegister() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 28; position++; buffer[position] = 2; position++; udp_send(writesocket, buffer, 4, &tempclient); free(buffer); printf("[USGN] Sent UPDATE request to %s...\n", inet_ntoa(tempclient.sin_addr)); return 0; } void ExecuteFunctionsWithTime(time_t *checktime, int writesocket) { time_t actualtime; time(&actualtime); if (*checktime != actualtime) //prevents executing more times than one in a second { if (actualtime % 5 == 0) //execute every 5 seconds { SendPingList(writesocket); SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status PingAllPlayer(writesocket); } else if (actualtime % 50 == 0) { UsgnUpdate(writesocket); } *checktime = actualtime; } } size_t u_strlen(unsigned char* buffer) { return strlen((char*) buffer); } diff --git a/src/main.c b/src/main.c index 0fe1bc3..05fd595 100644 --- a/src/main.c +++ b/src/main.c @@ -1,305 +1,295 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * - * Author/s of this file: Jermuk + * Author/s of this file: Jermuk, FloooD */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); - bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); + bind_socket(&readsocket, INADDR_ANY, sv_hostport); atexit(cleanup); //struct in_addr usgnip = GetIp("usgn.de"); /* FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); */ OnServerStart(); ReadMap(); UsgnRegister(readsocket); /** * \var needed for ExecuteFunctionsWithTime() */ time_t checktime; time(&checktime); int mstime = mtime(); int timecounter = mtime(); int tickcounter = 0; - const int fps = 1000 / FPS; + const int fps = 1000 / sv_fps; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; //1ms = 1000 while (1) { - if (mtime() - mstime >= fps) //Hope it does an constant fps + if ((timecounter + 1000 - (int) mtime()) <= 0) { - if ((timecounter + 10000 - (int) mtime()) <= 0) - { - fpsnow = (int) ceil(tickcounter / 10); - tickcounter = 0; - timecounter = mtime(); - } - tickcounter++; - mstime = mtime(); + fpsnow = (int) tickcounter; + tickcounter = 0; + timecounter = mtime(); + } + tickcounter++; - CheckForTimeout(readsocket); - ExecuteFunctionsWithTime(&checktime, readsocket); - CheckAllPlayerForReload(readsocket); + UpdateBuffer(); + CheckForTimeout(readsocket); + ExecuteFunctionsWithTime(&checktime, readsocket); + CheckAllPlayerForReload(readsocket); - FD_ZERO(&descriptor); - FD_SET(readsocket, &descriptor); - select(readsocket + 1, &descriptor, NULL, NULL, &timeout); + FD_ZERO(&descriptor); + FD_SET(readsocket, &descriptor); + select(readsocket + 1, &descriptor, NULL, NULL, &timeout); - if (FD_ISSET(readsocket, &descriptor)) - { - size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); + if (FD_ISSET(readsocket, &descriptor)) + { + size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); - if (size < 3) - { - printf("Invalid paket! (size < 3)\n"); - } - else + if (size < 3) + { + printf("Invalid paket! (size < 3)\n"); + } + else + { + int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown + if (id != -1)///When the player is known execute other commands as when the player is unknown { - int id = IsPlayerKnown(newclient.sin_addr, - newclient.sin_port); /// Function returns id or -1 if unknown - if (id != -1)///When the player is known execute other commands as when the player is unknown - { - if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary - { - PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation - player[id].lastpaket = mtime(); - int control = 1; - int position = 2; - /** - * This while construct splits the recieved UDP-message - * into cs2d-messages. - * Every packet function returns the count of read bytes. - */ - while (control) - { - int tempsize = size - position; - - unsigned char *message = malloc(tempsize); - memcpy(message, buffer + position, tempsize); - int rtn = 0; - - switch (message[0]) - //payload - { - case 1: - rtn = confirmation_known(message, tempsize, - id, readsocket); - break; - case 3: - rtn = connection_setup_known(message, - tempsize, newclient.sin_addr, - newclient.sin_port, id); - break; - case 7: - rtn = fire(message, tempsize, id, - readsocket); - break; - case 8: - rtn = advanced_fire(message, tempsize, id, - readsocket); - break; - case 9: - rtn = weaponchange(message, tempsize, id, - readsocket); - break; - case 10: - rtn = posupdaterun(message, tempsize, id, - readsocket); - break; - case 11: - rtn = posupdatewalk(message, tempsize, id, - readsocket); - break; - case 12: - rtn = rotupdate(message, tempsize, id, - readsocket); - break; - case 13: - rtn = posrotupdaterun(message, tempsize, - id, readsocket); - break; - case 14: - rtn = posrotupdatewalk(message, tempsize, - id, readsocket); - break; - case 16: - rtn = reload(message, tempsize, id, - readsocket); - break; - case 20: - rtn = teamchange(message, tempsize, id, - readsocket); - break; - case 23: - rtn - = buy(message, tempsize, id, - readsocket); - break; - case 28: - // Spray 28 - 0 - x x - y y - color - rtn = spray(message, tempsize, id, - readsocket); - break; - case 32: - rtn = specpos(message, tempsize, id, - readsocket); - break; - case 39: - rtn = respawnrequest(message, tempsize, id, - readsocket); - break; - case 240: - rtn = chatmessage(message, tempsize, id, - readsocket); - break; - case 249: - rtn = ping_ingame(message, tempsize, id, - readsocket); - break; - case 252: - rtn = joinroutine_known(message, tempsize, - id, readsocket); - break; - case 253: - rtn = leave(id, readsocket); - break; - default: - SendMessageToPlayer(id, - "Not implemented yet!", 1, - readsocket); - unknown(message, tempsize, buffer, size, - position); - rtn = tempsize; - break; - } - - position = position + rtn; - if (position == size) - { - free(message); - break; - } - /** - * Security check (Buffer Overflow) - */ - else if (position > size) - { - printf("Error while reading packet: position(%d) > size(%d)\n", position, size); - free(message); - } - free(message); - } - } - } - else + if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { + PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation + player[id].lastpaket = mtime(); int control = 1; int position = 2; + /** + * This while construct splits the recieved UDP-message + * into cs2d-messages. + * Every packet function returns the count of read bytes. + */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: - rtn = confirmation_unknown(message, tempsize, - newclient.sin_addr, newclient.sin_port); + rtn = confirmation_known(message, tempsize, id, + readsocket); break; case 3: - rtn = connection_setup_unknown(message, - tempsize, newclient.sin_addr, - newclient.sin_port); + rtn = connection_setup_known(message, tempsize, + newclient.sin_addr, newclient.sin_port, + id); + break; + case 7: + rtn = fire(message, tempsize, id, readsocket); + break; + case 8: + rtn = advanced_fire(message, tempsize, id, + readsocket); + break; + case 9: + rtn = weaponchange(message, tempsize, id, + readsocket); break; - case 27: - rtn = UsgnPacket(27, message, tempsize, readsocket); + case 10: + rtn = posupdaterun(message, tempsize, id, + readsocket); + break; + case 11: + rtn = posupdatewalk(message, tempsize, id, + readsocket); + break; + case 12: + rtn = rotupdate(message, tempsize, id, + readsocket); + break; + case 13: + rtn = posrotupdaterun(message, tempsize, id, + readsocket); + break; + case 14: + rtn = posrotupdatewalk(message, tempsize, id, + readsocket); + break; + case 16: + rtn = reload(message, tempsize, id, readsocket); + break; + case 20: + rtn = teamchange(message, tempsize, id, + readsocket); + break; + case 23: + rtn = buy(message, tempsize, id, readsocket); break; case 28: - rtn = UsgnPacket(28, message, tempsize, readsocket); + // Spray 28 - 0 - x x - y y - color + rtn = spray(message, tempsize, id, readsocket); break; - case 250: - rtn = ping_serverlist(message, tempsize, - &newclient, readsocket); + case 32: + rtn + = specpos(message, tempsize, id, + readsocket); break; - case 251: - rtn = serverinfo_request(message, tempsize, - &newclient, readsocket); + case 39: + rtn = respawnrequest(message, tempsize, id, + readsocket); + break; + case 240: + rtn = chatmessage(message, tempsize, id, + readsocket); + break; + case 249: + rtn = ping_ingame(message, tempsize, id, + readsocket); break; case 252: - rtn = joinroutine_unknown(message, tempsize, - &newclient, readsocket); + rtn = joinroutine_known(message, tempsize, id, + readsocket); + break; + case 253: + rtn = leave(id, readsocket); break; default: + SendMessageToPlayer(id, "Not implemented yet!", + 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } + else + { + int control = 1; + int position = 2; + while (control) + { + int tempsize = size - position; + unsigned char *message = malloc(tempsize); + memcpy(message, buffer + position, tempsize); + int rtn = 0; + + switch (message[0]) + //payload + { + case 1: + rtn = confirmation_unknown(message, tempsize, + newclient.sin_addr, newclient.sin_port); + break; + case 3: + rtn = connection_setup_unknown(message, tempsize, + newclient.sin_addr, newclient.sin_port); + break; + case 27: + rtn = UsgnPacket(27, message, tempsize, readsocket); + break; + case 28: + rtn = UsgnPacket(28, message, tempsize, readsocket); + break; + case 250: + rtn = ping_serverlist(message, tempsize, + &newclient, readsocket); + break; + case 251: + rtn = serverinfo_request(message, tempsize, + &newclient, readsocket); + break; + case 252: + rtn = joinroutine_unknown(message, tempsize, + &newclient, readsocket); + break; + default: + unknown(message, tempsize, buffer, size, position); + rtn = tempsize; + break; + } + + position = position + rtn; + if (position == size) + { + free(message); + break; + } + /** + * Security check (Buffer Overflow) + */ + else if (position > size) + { + printf("Error while reading packet: position(%d) > size(%d)\n", position, size); + free(message); + } + free(message); + } + } } + } else { #ifdef _WIN32 - Sleep(fps - (mtime() - mstime)); + Sleep(fps + mstime - mtime()); #else - sleep(fps - (mtime() - mstime)); + sleep(fps + mstime - mtime()); #endif } + mstime = mtime(); } return EXIT_SUCCESS; } diff --git a/src/script-functions.c b/src/script-functions.c index e34a8ee..fe0c8fb 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,569 +1,581 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * - * Author/s of this file: Jermuk + * Author/s of this file: Jermuk, FloooD */ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("Listening at port %d and using name '%s'\n", sv_hostport, sv_name); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) + { + if(player[id].money + mp_dmspawnmoney > 65000) player[id].money = 65000; + else player[id].money += mp_dmspawnmoney; return 0; + } else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; //printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; int temptime = mtime(); if (temptime < player[id].zoomtimer) { printf("Zoomtimer error!\n"); return 1; } else { player[id].zoomtimer = mtime() + 500; } switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); return 1; case 1: case 2: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; break; } case 4: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 5: { if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; break; } else if (player[id].zoommode == 2) { player[id].zoommode = 0; break; } return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); return 1; } } return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } int temptime = mtime(); if (temptime < player[id].firetimer) { printf("Firetimer error!\n"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; } int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; + int frames = fpsnow * player[id].latency / 1000; + if (frames > sv_lcbuffer) + { + frames = sv_lcbuffer; + } float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { - if (sqrt((player[b].x - startx) * (player[b].x - startx) - + (player[b].y - starty) * (player[b].y - starty)) + if (sqrt((player[b].buffer_x[frames] - startx)*(player[b].buffer_x[frames] - startx) + + (player[b].buffer_y[frames] - starty)*(player[b].buffer_y[frames] - starty)) <= 16) + /*if (sqrt((player[b].x - startx) * (player[b].x - startx) + + (player[b].y - starty) * (player[b].y - starty)) + <= 16)*/ { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); //printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].name != NULL) //test if weapon available { if (player[id].money - weapons[wpnid].price >= 0) { if (weapons[wpnid].team == 0 || weapons[wpnid].team == player[id].team) //Check if he is in the right team to buy this weapon { if (player[id].team == 1) { //Check if in buyzone int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { if (player[id].slot[g].id != wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { if (player[id].slot[g].id != wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } SendBuyFailedMessage(id, 255, writesocket); //Not in a buyzone return 1; } } else { SendBuyFailedMessage(id, 252, writesocket); //you cant buy this item return 1; } } else { SendBuyFailedMessage(id, 253, writesocket); //not enough money return 1; } } } //if nothing found SendBuyFailedMessage(id, 244, writesocket); /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone */ return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; if (player[hitter].money + 300 > 65000) player[hitter].money = 65000; else player[hitter].money += 300; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); SendKillMessage(hitter, victim, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK 1 - don't send it */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (u_strlen(message) >= 4 && strncmp((char *) message, "!log", 4) == 0) { char* log = malloc(u_strlen(message) - 5 + 1); //+1 for '\0' if (log == NULL) error_exit("Memory error ( OnChatMessage() -> log )\n"); strncpy(log, (char *) message + 5, u_strlen(message) - 5); log[u_strlen(message) - 5] = '\0'; eprintf("[LOG]: %s\n",log); free(log); return 1; } else if (u_strlen(message) >= 4 && strncmp((char *) message, "!fps", 4) == 0) { char buffer[30]; //Resulting stringlength unknown: Text = 24 chars sprintf(buffer, "Actually server FPS: %d", fpsnow); SendMessageToPlayer(id, buffer, 1, writesocket); return 1; } if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } diff --git a/src/settings.c b/src/settings.c index cf2bc75..c0de0cf 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,173 +1,179 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * - * Author/s of this file: Jermuk, GuccaGucca + * Author/s of this file: Jermuk, GuccaGucca, FloooD */ #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; char startweapons[] = {50}; int fpsnow = 0; unsigned char *sv_name = NULL; unsigned char *sv_map = NULL; unsigned int sv_hostport = 0; unsigned short sv_maxplayers = 0; +unsigned short sv_fps = 0; +unsigned short sv_lcbuffer = 0; unsigned short sv_fow = 0; unsigned short sv_gamemode = 0; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; unsigned char *sv_password = 0; unsigned short bot_count = 0; unsigned short mp_roundtime = 0; unsigned short mp_freezetime = 0; unsigned short mp_c4timer = 0; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; unsigned short mp_specmode = 0; unsigned short onlineplayer = 0; unsigned short mp_startmoney = 0; +unsigned short mp_dmspawnmoney = 0; struct setting { char *name; char *value; }; int tointeger(char * c); double todouble(char *c); struct setting * settings[256]; int entries; int readConfig() { FILE * pFile; char s[256]; int setting_num = 0; pFile = fopen("server.cfg","r"); if(pFile == NULL) perror("Error opening file: server.cfg"); else { while((fgets(s,sizeof(s),pFile))!= NULL) { if(s[0]=='\n' || (s[0] == '/' && s[1] == '/')) continue; //char *s1,*s2,*type; int i; for(i = 0; i < strlen(s);i++) { if(s[i] == ' ') { i++; //skip ' ' char struct setting * var; var = (struct setting*)malloc(sizeof(struct setting)); var->name = malloc(i+1); if(var->name == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->name,s,i); var->name[i] = '\0'; if(s[strlen(s)-i-1] == '\n') //if \n found then remove it { var->value = malloc(strlen(s)-i-1 +1); if(var->value == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->value,&s[i],strlen(s)-i-1); //also ommit the \n var->value[strlen(s)-i-1] = '\0'; } else { var->value = malloc(strlen(s)-i +1); if(var->value == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->value,&s[i],strlen(s)-i); //also ommit the \n var->value[strlen(s)-i] = '\0'; } settings[setting_num] = var; break; } } setting_num++; } fclose(pFile); } return setting_num; } char *GetValue(char *sname, char *alternate)////struct setting ** arr , int length) { int i; for(i = 0; i < entries; i++) { if(settings[i] != NULL) { struct setting *var = settings[i]; if(strcmp(var->name,sname)==0) { char *string = malloc(strlen(var->value)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, var->value, strlen(var->value)); string[strlen(var->value)] = '\0'; free(var->name); free(var->value); free(var); //also frees settings[i] settings[i] = NULL; return string; } } } //If not found char *string = malloc(strlen(alternate)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, alternate, strlen(alternate)); string[strlen(alternate)] = '\0'; return string; // doesn't exist } void ReadCfg() { entries = readConfig(); sv_name = (unsigned char *)GetValue("sv_name", "Alpha Custom CS2D Server"); sv_map = (unsigned char *)GetValue("sv_map", "de_cs2d"); sv_hostport = tointeger(GetValue("sv_hostport", "36963")); sv_maxplayers = tointeger(GetValue("sv_maxplayers", "32")) +1; + sv_fps = tointeger(GetValue("sv_fps", "250")); + sv_lcbuffer = tointeger(GetValue("sv_lcbuffer", "100")); sv_fow = tointeger(GetValue("sv_fow", "0")); sv_gamemode = tointeger(GetValue("sv_gamemode", "2")); sv_friendlyfire = tointeger(GetValue("sv_friendlyfire", "0")); sv_usgnonly = tointeger(GetValue("sv_usgnonly", "0")); sv_password = (unsigned char *)GetValue("sv_password", ""); bot_count = tointeger(GetValue("bot_count", "0")); mp_roundtime = tointeger(GetValue("mp_roundtime", "5")); mp_freezetime = tointeger(GetValue("mp_freezetime", "0")); mp_c4timer = tointeger(GetValue("mp_c4timer", "35")); mp_infammo = tointeger(GetValue("mp_infammo", "0")); mp_respawndelay = tointeger(GetValue("mp_respawndelay", "0")); mp_specmode = tointeger(GetValue("mp_specmode", "0")); mp_startmoney = tointeger(GetValue("mp_startmoney", "1000")); + mp_dmspawnmoney = tointeger(GetValue("mp_dmspawnmoney", "32000")); } int tointeger(char *c) { int buff = atoi(c); free(c); return buff; } double todouble(char *c) { double buff = atof(c); free(c); return buff; }
Jermuk/custom_cs2dsrv
560bc4ffb59e66b6e3e8f4f979d97f1dc211a269
Fixed buy problem and removed some messages.
diff --git a/src/respond_messages.c b/src/respond_messages.c index 08a3750..14f8bed 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -195,546 +195,546 @@ void SendWeaponChangeMessage(int id, int wpnid, int writesocket) int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if (status == 0) buffer[position] = 11; else if (status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if (status == 0) buffer[position] = 14; else if (status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; memcpy(buffer + position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer + position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch (status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch (status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + u_strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = u_strlen(player[id].name); position++; memcpy(buffer + position, player[id].name, u_strlen(player[id].name)); position += u_strlen(player[id].name); buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if (player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + u_strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = u_strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, u_strlen(message)); position += u_strlen(message); if (team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if (team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } // 28 - id - xx - yy - c void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket) { int stringsize = 8; unsigned char *buffer = malloc(stringsize * sizeof(char)); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position++] = 28; buffer[position++] = 0; buffer[position++] = id; memcpy(buffer + position, &xx, 2); position += 2; memcpy(buffer + position, &yy, 2); position += 2; buffer[position++] = c; // SendToAll(buffer, stringsize, 1, writesocket); -- Make sure that the spray-image send packet is crafted first. free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int victim, int writesocket) { char sHealth[4]; char sArmor[4]; //= player[id].health int sHealthLength = sprintf(sHealth, "%i", (int) player[id].health); int sArmorLength = sprintf(sArmor, "%i", (int) player[id].armor); int sNameLength = u_strlen(player[id].name); int length = 4 + sNameLength + sHealthLength + sArmorLength; // 4 for a6 spaces int stringsize = 17 + length; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); int position = 0; buffer[position] = 19; position++; buffer[position] = victim; position++; buffer[position] = id; position++; buffer[position] = player[id].slot[player[id].actualweapon].id; position++; memcpy(buffer + position, &player[victim].x, 2); position += 2; memcpy(buffer + position, &player[victim].y, 2); position += 2; unsigned short unknown1 = 240; memcpy(buffer + position, &unknown1, 2); position += 2; buffer[position] = 1; position++; memcpy(buffer + position, &length, 2); position += 2; buffer[position] = 'k'; position++; buffer[position] = 166; //166 acts like string seperator position++; memcpy(buffer + position, player[id].name, sNameLength); position += sNameLength; buffer[position] = 166; position++; memcpy(buffer + position, &sHealth, sHealthLength); position += sHealthLength; buffer[position] = 166; position++; memcpy(buffer + position, &sArmor, sArmorLength); position += sArmorLength; SendToPlayer(buffer, stringsize, victim, 1, writesocket); free(buffer); stringsize = 8; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); position = 0; buffer[position] = 19; position++; buffer[position] = victim; position++; buffer[position] = id; position++; buffer[position] = player[id].slot[player[id].actualweapon].id; position++; memcpy(buffer + position, &player[victim].x, 2); position += 2; memcpy(buffer + position, &player[victim].y, 2); position += 2; SendToAllOther(victim, buffer, stringsize, 1, writesocket); free(buffer); } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count * 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer + position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); } void SendBuyFailedMessage(int id, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyFailedMessage() )\n"); int position = 0; buffer[position] = 23; position++; - buffer[position] = 1; + buffer[position] = id; position++; buffer[position] = status; position++; buffer[position] = 44; position++; buffer[position] = 1; position++; buffer[position] = 0; position++; //TODO what does the last lines mean? /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone * */ SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); } diff --git a/src/script-functions.c b/src/script-functions.c index 138125a..e34a8ee 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,562 +1,569 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("Listening at port %d and using name '%s'\n", sv_hostport, sv_name); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; - printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); + //printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; int temptime = mtime(); if (temptime < player[id].zoomtimer) { printf("Zoomtimer error!\n"); return 1; } else { player[id].zoomtimer = mtime() + 500; } switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); return 1; case 1: case 2: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; break; } case 4: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 5: { if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; break; } else if (player[id].zoommode == 2) { player[id].zoommode = 0; break; } return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); return 1; } } return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } int temptime = mtime(); if (temptime < player[id].firetimer) { printf("Firetimer error!\n"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; } int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if (sqrt((player[b].x - startx) * (player[b].x - startx) + (player[b].y - starty) * (player[b].y - starty)) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); - printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); + //printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { - int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].name != NULL) //test if weapon available { if (player[id].money - weapons[wpnid].price >= 0) { if (weapons[wpnid].team == 0 || weapons[wpnid].team == player[id].team) //Check if he is in the right team to buy this weapon { if (player[id].team == 1) { //Check if in buyzone int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { - return 0; + int g; + for (g = 0; g <= 99; g++) + { + if (player[id].slot[g].id != wpnid) + { + return 0; + } + } + SendBuyFailedMessage(id, 251, writesocket); //You have it already + return 1; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { - if (player[id].slot[player[id].actualweapon].id - == wpnid) + if (player[id].slot[g].id != wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } - SendBuyFailedMessage(id, 255, writesocket); + SendBuyFailedMessage(id, 255, writesocket); //Not in a buyzone return 1; } } else { - SendBuyFailedMessage(id, 252, writesocket); + SendBuyFailedMessage(id, 252, writesocket); //you cant buy this item return 1; } } else { - SendBuyFailedMessage(id, 253, writesocket); + SendBuyFailedMessage(id, 253, writesocket); //not enough money return 1; } } } //if nothing found SendBuyFailedMessage(id, 244, writesocket); /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone */ return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; if (player[hitter].money + 300 > 65000) player[hitter].money = 65000; else player[hitter].money += 300; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); SendKillMessage(hitter, victim, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK 1 - don't send it */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (u_strlen(message) >= 4 && strncmp((char *) message, "!log", 4) == 0) { char* log = malloc(u_strlen(message) - 5 + 1); //+1 for '\0' if (log == NULL) error_exit("Memory error ( OnChatMessage() -> log )\n"); strncpy(log, (char *) message + 5, u_strlen(message) - 5); log[u_strlen(message) - 5] = '\0'; eprintf("[LOG]: %s\n",log); free(log); return 1; } else if (u_strlen(message) >= 4 && strncmp((char *) message, "!fps", 4) == 0) { char buffer[30]; //Resulting stringlength unknown: Text = 24 chars sprintf(buffer, "Actually server FPS: %d", fpsnow); SendMessageToPlayer(id, buffer, 1, writesocket); return 1; } if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; }
Jermuk/custom_cs2dsrv
9a85641352ae7af6419abaff4340c1cfb0f985b7
Fixed usgn support, memory leaks and changed the resolution from player[id].lastpaket to ms (tolerance +-1).
diff --git a/include/functions.h b/include/functions.h index f4f1272..6ab13f9 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,33 +1,35 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(int writesocket); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(unsigned char *message, int id); void PaketConfirmation(unsigned char *message, int id, int writesocket); int CheckPlayerData(unsigned char *password); unsigned char *GetEncodedString(unsigned char *string, int length); void CheckAllPlayerForReload(int writesocket); struct in_addr GetIp(char *name); -int UsgnRegister(struct in_addr ip, int writesocket); +int UsgnRegister(int writesocket); +int UsgnUpdate(int writesocket); +void ExecuteFunctionsWithTime(time_t *checktime, int writesocket); size_t u_strlen(unsigned char* buffer); #endif // FUNCTIONS_H_INCLUDED diff --git a/include/pakets.h b/include/pakets.h index b4d980c..5602652 100644 --- a/include/pakets.h +++ b/include/pakets.h @@ -1,52 +1,53 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef PAKETS_H_INCLUDED #define PAKETS_H_INCLUDED #include "main.h" //#include "" int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position); int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id); int ping_ingame(unsigned char *message, int length, int id, int writesocket); int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int confirmation_known(unsigned char *message, int length, int id, int writesocket); int fire(unsigned char *message, int length, int id, int writesocket); int advanced_fire(unsigned char *message, int length, int id, int writesocket); int buy(unsigned char *message, int length, int id, int writesocket); int rotupdate(unsigned char *message, int length, int id, int writesocket); int posupdatewalk(unsigned char *message, int length, int id, int writesocket); int posupdaterun(unsigned char *message, int length, int id, int writesocket); int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket); int posrotupdaterun(unsigned char *message, int length, int id, int writesocket); int respawnrequest(unsigned char *message, int length, int id, int writesocket); int weaponchange(unsigned char *message, int length, int id, int writesocket); int teamchange(unsigned char *message, int length, int id, int writesocket); int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int specpos(unsigned char *message, int length, int id, int writesocket); int chatmessage(unsigned char *message, int length, int id, int writesocket); int joinroutine_known(unsigned char *message, int length, int id, int writesocket); int leave(int id, int writesocket); int reload(unsigned char *message, int length, int id, int writesocket); int spray(unsigned char *message, int length, int id, int writesocket); +int UsgnPacket(int packetid, unsigned char *message, int length, int writesocket); #endif // PAKETS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index d252f2f..705c9f6 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,39 +1,39 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); void SendAdvancedFireMessage(int id, int status, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, char *message, int status, int writesocket); void SendMessageToAll(char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); -void PingAllPlayer(int writesocket, time_t *firsttime); +void PingAllPlayer(int writesocket); void SendReloadMessage(int id, int status, int writesocket); void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket); void SendKillMessage(int id, int victim, int writesocket); void SendPingList(int writesocket); void SendBuyFailedMessage(int id, int status, int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/structs.h b/include/structs.h index e9ac3c3..f2c6ffa 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,102 +1,102 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" #define MAX_CLIENTS 64 struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; short freq; //every freq ms one shoot short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; short special; short team; }; /* * team * 0 - everyone can buy it * 1 - t-only * 2 - ct only * 3 - unbuyable */ struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; short special; }; /* * special * 0 = Normal * 1 = Silencer * 2 = Burst * 3 = Melee * 4 = 1xZoom * 5 = 2xZoom * 6 = Shotgun */ struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; - time_t lastpaket; + int lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; unsigned short deaths; short score; unsigned short x, y; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; unsigned short kills; int reloadtimer, reloading; short dead; int start; unsigned short latency; int firetimer, zoomtimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/src/functions.c b/src/functions.c index 45b56d9..a50cdb9 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,482 +1,537 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; player[id].zoomtimer = 0; player[id].firetimer = 0; int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; player[id].slot[i].special = 0; player[id].zoommode = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * */ int PlayerTimeout(int id) { //id = 0; - time_t actualtime; - time(&actualtime); + int actualtime = mtime(); - if (((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket + if (((player[id].lastpaket + TIMEOUT*1000) < actualtime) && player[id].lastpaket != 0) { return 1; } return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if (strcmp((char*) sv_password, "")) { serverstatus += 1; } if (sv_usgnonly == 1) { serverstatus += 2; } if (sv_fow == 1) { serverstatus += 4; } if (sv_friendlyfire == 1) { serverstatus += 8; } if (1) //Same Version? { serverstatus += 16; } if (sv_gamemode != 0) { serverstatus += 32; } if (0) //LuaScripts { serverstatus += 64; } if (1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x >> 8) | (*x << 8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x << 24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(unsigned char *message, int id) { - unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + /* + unsigned short *pTempNummer = malloc(2); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; + */ + unsigned short *pTempNummer = (unsigned short *)message; if (*pTempNummer % 2 != 0) { if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer + 2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); - free(pTempNummer); + //free(pTempNummer); return 0; } } if (*pTempNummer - 1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ - free(pTempNummer); + //free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(unsigned char *message, int id, int writesocket) { + unsigned short *pTempNummer = (unsigned short *)message; + /* unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; + */ if (*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer + 1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } - free(pTempNummer); + //free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(unsigned char *password) { if (strcmp((char*) sv_password, (char*) password) != 0) { printf("Password wrong!\n"); return 1; } if (sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length + 1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(int writesocket) * \brief check all player if their reload is ended, * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].reloading != 0) { if (player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if (player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } struct in_addr GetIp(char *name) { struct in_addr ip; struct hostent *dnsresolve; if ((dnsresolve = gethostbyname(name)) == NULL) { printf("Error: Failed to resolve %s!\n", name); ip.s_addr = inet_addr("85.214.102.60"); return ip; //return usgn ip } memcpy(&ip, dnsresolve->h_addr_list[0], dnsresolve->h_length); return ip; } -int UsgnRegister(struct in_addr ip, int writesocket) +int UsgnRegister(int writesocket) { struct sockaddr_in tempclient; tempclient.sin_family = AF_INET; - tempclient.sin_port = 36963; - tempclient.sin_addr = ip; + tempclient.sin_port = htons(36963); + tempclient.sin_addr = GetIp("usgn.de"); unsigned char *buffer = malloc(4); if (buffer == NULL) error_exit("Memory error ( UsgnRegister() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 27; position++; buffer[position] = 1; position++; udp_send(writesocket, buffer, 4, &tempclient); free(buffer); - printf("[USGN] Sent ADD request to %s...\n", inet_ntoa(ip)); + printf("[USGN] Sent ADD request to %s...\n", inet_ntoa(tempclient.sin_addr)); return 0; } +int UsgnUpdate(int writesocket) +{ + struct sockaddr_in tempclient; + + tempclient.sin_family = AF_INET; + tempclient.sin_port = htons(36963); + tempclient.sin_addr = GetIp("usgn.de"); + + unsigned char *buffer = malloc(4); + if (buffer == NULL) + error_exit("Memory error ( UsgnRegister() )"); + int position = 0; + + buffer[position] = 1; + position++; + buffer[position] = 0; + position++; + buffer[position] = 28; + position++; + buffer[position] = 2; + position++; + + udp_send(writesocket, buffer, 4, &tempclient); + free(buffer); + + printf("[USGN] Sent UPDATE request to %s...\n", inet_ntoa(tempclient.sin_addr)); + return 0; +} + +void ExecuteFunctionsWithTime(time_t *checktime, int writesocket) +{ + time_t actualtime; + time(&actualtime); + if (*checktime != actualtime) //prevents executing more times than one in a second + { + if (actualtime % 5 == 0) //execute every 5 seconds + { + SendPingList(writesocket); + SendMessageToAll("This is an alpha version! Don't play at it!", 1, + writesocket); //Do not remove or change this until server reaches beta status + PingAllPlayer(writesocket); + } + else if (actualtime % 50 == 0) + { + UsgnUpdate(writesocket); + } + *checktime = actualtime; + } +} + size_t u_strlen(unsigned char* buffer) { return strlen((char*) buffer); } diff --git a/src/main.c b/src/main.c index 5a0c4dc..0fe1bc3 100644 --- a/src/main.c +++ b/src/main.c @@ -1,312 +1,305 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ - #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); - struct in_addr usgnip = GetIp("usgn.de"); + //struct in_addr usgnip = GetIp("usgn.de"); /* FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); */ OnServerStart(); ReadMap(); - //UsgnRegister(usgnip, readsocket); + UsgnRegister(readsocket); /** - * \var needed for PingAllPlayer() to execute it every 5 sec + * \var needed for ExecuteFunctionsWithTime() */ - time_t firsttime; - time(&firsttime); + time_t checktime; + time(&checktime); int mstime = mtime(); int timecounter = mtime(); int tickcounter = 0; - const int fps = 1000/FPS; + const int fps = 1000 / FPS; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; //1ms = 1000 while (1) { if (mtime() - mstime >= fps) //Hope it does an constant fps { - if ((timecounter+10000 - (int)mtime()) <= 0) + if ((timecounter + 10000 - (int) mtime()) <= 0) { - fpsnow = (int)ceil(tickcounter/10); + fpsnow = (int) ceil(tickcounter / 10); tickcounter = 0; timecounter = mtime(); } tickcounter++; mstime = mtime(); CheckForTimeout(readsocket); - PingAllPlayer(readsocket, &firsttime); /// also execute PingList() + ExecuteFunctionsWithTime(&checktime, readsocket); CheckAllPlayerForReload(readsocket); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); select(readsocket + 1, &descriptor, NULL, NULL, &timeout); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation - time(&player[id].lastpaket); + player[id].lastpaket = mtime(); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 28: // Spray 28 - 0 - x x - y y - color rtn = spray(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } - /* - else if(!strcmp(inet_ntoa(usgnip), inet_ntoa(newclient.sin_addr))) - { - printf("[USGN] Message recieved: "); - int i; - for(i = 0; i < size; i++) - { - eprintf("%d-", buffer[i]); - } - eprintf("\n"); - } - */ else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; + case 27: + rtn = UsgnPacket(27, message, tempsize, readsocket); + break; + case 28: + rtn = UsgnPacket(28, message, tempsize, readsocket); + break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } else { #ifdef _WIN32 Sleep(fps - (mtime() - mstime)); #else sleep(fps - (mtime() - mstime)); #endif } } return EXIT_SUCCESS; } diff --git a/src/pakets.c b/src/pakets.c index 346a853..190779a 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -77,1666 +77,1710 @@ int connection_setup_known(unsigned char *message, int length, return length; } return paketlength; } /** * \fn int ping_ingame(unsigned char *message, int length, int id, int writesocket) * \brief handles a answer from the server ingame ping. this function calculates the latency * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_ingame(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; if (length < paketlength) { printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; //printf("%s: %d\n", player[id].name, player[id].latency); return paketlength; } /** * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a confirmation for unknown player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } /** * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) * \brief handles a confirmation for known player * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } /** * \fn int fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a fire * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if (length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch (OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } /** * \fn int advanced_fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a advanced_fire (right click) * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int advanced_fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (length < paketlength) { printf("Invalid packet (advanced_fire)!\n"); return length; } unsigned int status = message[1]; switch (OnAdvancedFire(id, status, writesocket)) { case 0: SendAdvancedFireMessage(id, status, writesocket); break; case 1: break; } return paketlength; } /** * \fn int buy(unsigned char *message, int length, int id, int writesocket) * \brief handles a buy request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch (OnBuyAttempt(id, wpnid, writesocket)) { case 0: OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } /** * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) * \brief handles a rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if (length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message + 1, sizeof(float)); if (temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } /** * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) * \brief handles a position walk update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if (length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } /** * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) * \brief handles a position run update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if (length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } /** * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position walk and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if (length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); memcpy(&rotation, message + 5, sizeof(float)); if (rotation >= -180 && rotation <= 180) { switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position run and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if (length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); memcpy(&rotation, message + 5, sizeof(float)); if (rotation >= -180 && rotation <= 180) { switch (OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) * \brief handles a respawn request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if (length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch (OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch (player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp] + 0.5) * 32; player[id].y = (tspawny[tmp] + 0.5) * 32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp] + 0.5) * 32; player[id].y = (ctspawny[tmp] + 0.5) * 32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } /** * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a weapon change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch (OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch (OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if (skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param *client pointer to the client information structure * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if (length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if (tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; - memcpy(tempbuffer + 2, message, paketlength); + memcpy(tempbuffer + 2, message, paketlength-2); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if (length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); if (sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch (message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = u_strlen(sv_name); position++; memcpy(buffer + position, sv_name, u_strlen(sv_name)); position += u_strlen(sv_name); buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if (sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if (length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch (message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS - 1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + u_strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if (paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch (OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength = 4; unsigned char team, unknown; int paketsize; if (paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length - position + 1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( chatmessage() )\n"); memcpy(string, message + position, paketsize); string[paketsize] = '\0'; position += paketsize; switch (OnChatMessage(id, string, team, writesocket)) { case 0: SendChatMessage(id, string, team, writesocket); break; case 1: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch (message[1]) { case 0: { paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if (player[id].joinstatus == 1) { paketlength = 16; // ??? if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; - player[id].name = malloc(stringsize); + player[id].name = malloc(stringsize+1); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message + position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; - unsigned char *password = malloc(stringsize); + unsigned char *password = malloc(stringsize+1); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message + position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; for (i = 0; i <= u_strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; - unsigned char *encryption1 = malloc(stringsize); + unsigned char *encryption1 = malloc(stringsize+1); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message + position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message + position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes /* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif */ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; - player[id].spraylogo = malloc(stringsize); + player[id].spraylogo = malloc(stringsize+1); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message + position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; - unsigned char *maphash = malloc(stringsize); + unsigned char *maphash = malloc(stringsize+1); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; - player[id].win = malloc(stringsize); + player[id].win = malloc(stringsize+1); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message + position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch (tempstatus) { case 0x00: stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); position += u_strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } //stringsize = 16 + u_strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if (stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if (player[id].joinstatus == 2) { int position = 2; paketlength = 5; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } position++; - unsigned char *maphash = malloc(stringsize); + unsigned char *maphash = malloc(stringsize+1); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMaphash: %s\n", maphash); //pre_authcode_respond stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("pre_authcon_respond too big\n"); return length; } position++; - unsigned char *pre_authcode_respond = malloc(stringsize); + unsigned char *pre_authcode_respond = malloc(stringsize+1); if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(pre_authcode_respond, message + position, stringsize); pre_authcode_respond[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); //Player Version //unsigned char mapstatus = message[position]; //avoid warning position++; //printf("\tMapstatus: %d\n", mapstatus); free(pre_authcode_respond); free(maphash); //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if (player[id].joinstatus == 3) { int position = 2; paketlength = 3; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Mapname too big\n"); return length; } position++; - unsigned char *mapname = malloc(stringsize); + unsigned char *mapname = malloc(stringsize+1); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message + position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(sv_name); position++; memcpy(buffer + position, sv_name, u_strlen(sv_name)); position += u_strlen(sv_name); buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_friendlyfire; position++; buffer[position] = 0; //Unknown position++; buffer[position] = mp_roundtime; position++; buffer[position] = mp_freezetime; position++; buffer[position] = mp_c4timer; position++; buffer[position] = 32; //Unknown position++; buffer[position] = 124; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 1; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_maxplayers; position++; buffer[position] = sv_fow; position++; buffer[position] = mp_specmode; position++; buffer[position] = sv_gamemode; position++; buffer[position] = mp_respawndelay; position++; buffer[position] = mp_infammo; position++; buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; position++; buffer[position] = onlineplayer; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 1 && i != id) { unsigned char *encodedname; encodedname = GetEncodedString(player[i].name, u_strlen( player[i].name)); unsigned short *deaths = &player[i].deaths; unsigned short tempscore = (unsigned) (player[i].deaths + 1000); unsigned short *score = &tempscore; unsigned short tempx = (player[i].x); unsigned short tempy = (player[i].y); unsigned short *x = &tempx; unsigned short *y = &tempy; float *ptemprotation = &player[i].rotation; int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = i; position++; buffer[position] = u_strlen(encodedname); position++; memcpy(buffer + position, encodedname, u_strlen(encodedname)); position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[i].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; /* buffer[position] = score[0]; //Deaths position++; buffer[position] = score[1]; //Deaths position++; */ memcpy(buffer + position, score, 2); position += 2; /* buffer[position] = deaths[0]; //Deaths position++; buffer[position] = deaths[1]; //Deaths position++; */ memcpy(buffer + position, deaths, 2); position += 2; memcpy(buffer + position, x, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; memcpy(buffer + position, y, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = ptemprotation[0]; //Rotation position++; buffer[position] = ptemprotation[1]; //Rotation position++; buffer[position] = player[i].health; //Health position++; buffer[position] = player[i].armor; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe position++; buffer[position] = 0; //Unknown position++; /* 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 e8 03 00 00 12 01 00 00 01 03 e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 */ } } if (1) { unsigned char *encodedname; encodedname = GetEncodedString(player[id].name, u_strlen( player[id].name)); int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = id; position++; buffer[position] = u_strlen(encodedname); position++; memcpy(buffer + position, encodedname, u_strlen(encodedname)); position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[id].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 232; //Unknown position++; buffer[position] = 3; //Unknown position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //X position++; buffer[position] = 0; //X position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Health position++; buffer[position] = 0; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Aktuelle Waffe 50 = Knife position++; buffer[position] = 0; //Unknown position++; } SendToPlayer(buffer, position, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- HostageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 2; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ItemData ----------- /* fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 */ stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 3; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- EnityData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 4; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 5; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ProjectileData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 6; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectImageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 7; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- Final ACK ----------- stringsize = 7; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 200; //third payload position++; buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); player[id].joinstatus = 4; free(mapname); OnJoin(id, writesocket); } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } default: { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } return paketlength; } int leave(int id, int writesocket) { OnLeave(id, writesocket); free(player[id].name); free(player[id].usgn); free(player[id].spraylogo); free(player[id].win); player[id].name = NULL; player[id].usgn = NULL; player[id].spraylogo = NULL; player[id].win = NULL; onlineplayer--; ClearPlayer(id); return 2; } int reload(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int status; status = message[position]; position++; if (status == 1) { SendReloadMessage(id, 1, writesocket); player[id].reloading = player[id].actualweapon; player[id].reloadtimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].reloadtime; } return paketlength; } int spray(unsigned char *message, int length, int id, int writesocket) { // 28 0 xx yy c // 0 1 23 45 6 - struct{ - unsigned char hi; unsigned char lo; + struct + { + unsigned char hi; + unsigned char lo; } x, y; if (length < 7) { printf("Invalid packet (spray)!\n"); return length; } x.lo = message[2]; x.hi = message[3]; y.lo = message[4]; y.hi = message[5]; - unsigned short xx = x.hi*256+x.lo, yy = y.hi*256+y.lo; + unsigned short xx = x.hi * 256 + x.lo, yy = y.hi * 256 + y.lo; unsigned char c = message[6]; - unsigned char i = (char)id; + unsigned char i = (char) id; // Postprocessing if needed, then send back exact same data // xx and yy are positions, not tiles. SendSprayMessage(i, xx, yy, c, writesocket); return 7; } + +int UsgnPacket(int packetid, unsigned char *message, int length, + int writesocket) //No check if really from usgn.de +{ + int paketlength = 2; + switch (packetid) + { + case 27: + if (message[1] == 1) + { + printf("[USGN] Server successfully added to the serverlist..\n"); + } + else + { + printf("[USGN] Server NOT added to the serverlist.. (Code: %d)\n", message[3]); + } + paketlength = 2; + break; + case 28: + if (message[1] == 2) + { + printf("[USGN] Server successfully updated in the serverlist..\n"); + } + else + { + printf("[USGN] Server NOT updated in the serverlist.. (Code: %d)\n", message[3]); + } + paketlength = 2; + break; + default: + printf("[USGN] Unknown Message recieved: "); + int i; + for (i = 0; i < length; i++) + { + eprintf("%d-", message[i]); + } + eprintf("\n"); + paketlength = length; + break; + } + return paketlength; +} diff --git a/src/respond_messages.c b/src/respond_messages.c index 1fccad6..08a3750 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,750 +1,740 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer + position, spawnx, 2); position += 2; memcpy(buffer + position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer + position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for (i = 0; i <= count - 1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if (startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendAdvancedFireMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 8; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer + position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if (status == 0) buffer[position] = 11; else if (status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if (status == 0) buffer[position] = 14; else if (status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; memcpy(buffer + position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer + position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch (status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch (status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + u_strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = u_strlen(player[id].name); position++; memcpy(buffer + position, player[id].name, u_strlen(player[id].name)); position += u_strlen(player[id].name); buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if (player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + u_strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = u_strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, u_strlen(message)); position += u_strlen(message); if (team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if (team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } -void PingAllPlayer(int writesocket, time_t *firsttime) +void PingAllPlayer(int writesocket) { - time_t actualtime; - time(&actualtime); - if (actualtime >= (*firsttime + 5)) + int i; + for (i = 1; i <= sv_maxplayers; i++) { - *firsttime = actualtime; - SendPingList(writesocket); - - SendMessageToAll("This is an alpha version! Don't play at it!", 1, - writesocket); //Do not remove or change this until server reaches beta status - int i; - for (i = 1; i <= sv_maxplayers; i++) + if (player[i].used == 1 && player[i].joinstatus >= 4) { - if (player[i].used == 1 && player[i].joinstatus >= 4) - { - int stringsize = 5; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendJoinMessage() )\n"); - - int position = 0; + int stringsize = 5; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendJoinMessage() )\n"); - buffer[position] = 249; - position++; - buffer[position] = 0; - position++; - buffer[position] = 32; - position++; - buffer[position] = 191; - position++; - buffer[position] = 0; - position++; + int position = 0; - player[i].start = mtime(); + buffer[position] = 249; + position++; + buffer[position] = 0; + position++; + buffer[position] = 32; + position++; + buffer[position] = 191; + position++; + buffer[position] = 0; + position++; - SendToPlayer(buffer, stringsize, i, 0, writesocket); + player[i].start = mtime(); - free(buffer); - } + SendToPlayer(buffer, stringsize, i, 0, writesocket); + free(buffer); } + } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } // 28 - id - xx - yy - c void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket) { int stringsize = 8; unsigned char *buffer = malloc(stringsize * sizeof(char)); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position++] = 28; buffer[position++] = 0; buffer[position++] = id; memcpy(buffer + position, &xx, 2); position += 2; memcpy(buffer + position, &yy, 2); position += 2; buffer[position++] = c; // SendToAll(buffer, stringsize, 1, writesocket); -- Make sure that the spray-image send packet is crafted first. free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int victim, int writesocket) { char sHealth[4]; char sArmor[4]; //= player[id].health int sHealthLength = sprintf(sHealth, "%i", (int) player[id].health); int sArmorLength = sprintf(sArmor, "%i", (int) player[id].armor); int sNameLength = u_strlen(player[id].name); int length = 4 + sNameLength + sHealthLength + sArmorLength; // 4 for a6 spaces int stringsize = 17 + length; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); int position = 0; buffer[position] = 19; position++; buffer[position] = victim; position++; buffer[position] = id; position++; buffer[position] = player[id].slot[player[id].actualweapon].id; position++; memcpy(buffer + position, &player[victim].x, 2); position += 2; memcpy(buffer + position, &player[victim].y, 2); position += 2; unsigned short unknown1 = 240; memcpy(buffer + position, &unknown1, 2); position += 2; buffer[position] = 1; position++; memcpy(buffer + position, &length, 2); position += 2; buffer[position] = 'k'; position++; buffer[position] = 166; //166 acts like string seperator position++; memcpy(buffer + position, player[id].name, sNameLength); position += sNameLength; buffer[position] = 166; position++; memcpy(buffer + position, &sHealth, sHealthLength); position += sHealthLength; buffer[position] = 166; position++; memcpy(buffer + position, &sArmor, sArmorLength); position += sArmorLength; SendToPlayer(buffer, stringsize, victim, 1, writesocket); free(buffer); stringsize = 8; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); position = 0; buffer[position] = 19; position++; buffer[position] = victim; position++; buffer[position] = id; position++; buffer[position] = player[id].slot[player[id].actualweapon].id; position++; memcpy(buffer + position, &player[victim].x, 2); position += 2; memcpy(buffer + position, &player[victim].y, 2); position += 2; - SendToAllOther(victim, buffer, stringsize, 1, writesocket); + SendToAllOther(victim, buffer, stringsize, 1, writesocket); free(buffer); } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count * 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer + position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); } void SendBuyFailedMessage(int id, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyFailedMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = 1; position++; buffer[position] = status; position++; buffer[position] = 44; position++; buffer[position] = 1; position++; buffer[position] = 0; position++; //TODO what does the last lines mean? /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone * */ SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); } diff --git a/src/script-functions.c b/src/script-functions.c index 6ee0fb3..138125a 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,561 +1,562 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); + printf("Listening at port %d and using name '%s'\n", sv_hostport, sv_name); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; int temptime = mtime(); if (temptime < player[id].zoomtimer) { printf("Zoomtimer error!\n"); return 1; } else { player[id].zoomtimer = mtime() + 500; } switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); return 1; case 1: case 2: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; break; } case 4: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 5: { if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; break; } else if (player[id].zoommode == 2) { player[id].zoommode = 0; break; } return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); return 1; } } return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } int temptime = mtime(); if (temptime < player[id].firetimer) { printf("Firetimer error!\n"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; } int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if (sqrt((player[b].x - startx) * (player[b].x - startx) + (player[b].y - starty) * (player[b].y - starty)) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].name != NULL) //test if weapon available { if (player[id].money - weapons[wpnid].price >= 0) { if (weapons[wpnid].team == 0 || weapons[wpnid].team == player[id].team) //Check if he is in the right team to buy this weapon { if (player[id].team == 1) { //Check if in buyzone int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { return 0; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { if (player[id].slot[player[id].actualweapon].id == wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } } else { SendBuyFailedMessage(id, 252, writesocket); return 1; } } else { SendBuyFailedMessage(id, 253, writesocket); return 1; } } } //if nothing found SendBuyFailedMessage(id, 244, writesocket); /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone */ return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; if (player[hitter].money + 300 > 65000) player[hitter].money = 65000; else player[hitter].money += 300; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); SendKillMessage(hitter, victim, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK 1 - don't send it */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (u_strlen(message) >= 4 && strncmp((char *) message, "!log", 4) == 0) { - char* log = malloc(u_strlen(message) - 5 + 1); + char* log = malloc(u_strlen(message) - 5 + 1); //+1 for '\0' if (log == NULL) error_exit("Memory error ( OnChatMessage() -> log )\n"); - strncpy(log, (char *) message + 5, u_strlen(message) - 5 + 1); - log[u_strlen(message) - 5 + 1] = '\0'; + strncpy(log, (char *) message + 5, u_strlen(message) - 5); + log[u_strlen(message) - 5] = '\0'; eprintf("[LOG]: %s\n",log); free(log); return 1; } else if (u_strlen(message) >= 4 && strncmp((char *) message, "!fps", 4) == 0) { char buffer[30]; //Resulting stringlength unknown: Text = 24 chars sprintf(buffer, "Actually server FPS: %d", fpsnow); SendMessageToPlayer(id, buffer, 1, writesocket); return 1; } if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; }
Jermuk/custom_cs2dsrv
e972bb8304adb90410f87e6ef05009d5b963cba5
made sleep() function unix compatible and added non-working usgn support.
diff --git a/include/cross_layer.h b/include/cross_layer.h index 5ed389b..eda8907 100644 --- a/include/cross_layer.h +++ b/include/cross_layer.h @@ -1,23 +1,24 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef CROSS_LAYER_H_INCLUDED #define CROSS_LAYER_H_INCLUDED #include "main.h" int create_socket(void); void error_exit(char *message); void bind_socket(int *sock, unsigned long adress, unsigned short port); +void socket_error_exit(char *message); void cleanup(void); int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client); void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client); unsigned int mtime(void); #endif // CROSS_LAYER_H_INCLUDED diff --git a/include/functions.h b/include/functions.h index 2463141..f4f1272 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,32 +1,33 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(int writesocket); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(unsigned char *message, int id); void PaketConfirmation(unsigned char *message, int id, int writesocket); int CheckPlayerData(unsigned char *password); unsigned char *GetEncodedString(unsigned char *string, int length); void CheckAllPlayerForReload(int writesocket); -int UsgnRegister(int writesocket); +struct in_addr GetIp(char *name); +int UsgnRegister(struct in_addr ip, int writesocket); size_t u_strlen(unsigned char* buffer); #endif // FUNCTIONS_H_INCLUDED diff --git a/src/cross_layer.c b/src/cross_layer.c index 4db7e16..e9581ec 100644 --- a/src/cross_layer.c +++ b/src/cross_layer.c @@ -1,211 +1,229 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/cross_layer.h" /** * \fn int create_socket(void) * \brief creates a socket * \return socketnumber or 0 if failed */ int create_socket(void) { #ifdef _WIN32 WSADATA wsa; if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) { - error_exit("WSAStartup() failed"); + socket_error_exit("WSAStartup() failed"); } else { int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { - error_exit("socket() failed"); + socket_error_exit("socket() failed"); } return sock; } #else const int y = 1; int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { - error_exit("socket() failed"); + socket_error_exit("socket() failed"); } setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); return sock; #endif return 0; } /** * \fn int bind_socket(int *sock, unsigned long adress, unsigned short port) * \brief bind a socket to a specific IP and port * \param *sock socket to bind * \param adress ip-address to bind * \param port port to bind */ void bind_socket(int *sock, unsigned long adress, unsigned short port) { #ifdef _WIN32 struct sockaddr_in server; memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) { - error_exit("bind() failed"); + socket_error_exit("bind() failed"); } #else struct sockaddr_in server; memset(&server, 0, sizeof (server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) { - error_exit("bind() failed"); + socket_error_exit("bind() failed"); } #endif } /** * \fn int error_exit(char *message) * \brief Show a error message and exit the programm * \param *message message to display */ void error_exit(char *message) { printf("%s", message); /* printf("%s: %d\n", message, WSAGetLastError()); //debug(stderr); #else printf("%s: %s\n", message, strerror(errno)); //debug(stderr); */ exit(EXIT_FAILURE); } +/** + * \fn int socket_error_exit(char *message) + * \brief Show a error message and exit the programm + * \param *message message to display + */ +void socket_error_exit(char *message) +{ +#ifdef _WIN32 + printf("%s: %d\n", message, WSAGetLastError()); + //debug(stderr); +#else + printf("%s: %s\n", message, strerror(errno)); + //debug(stderr); +#endif + + exit(EXIT_FAILURE); +} + /** * \fn cleanup(void) * \brief clean the socket */ void cleanup(void) { OnExit(); #ifdef _WIN32 WSACleanup(); #else /* Nichts zu tun */ #endif } /** * \fn mtime(void) * \brief return the actually time in miliseconds for win and linux * \return time in ms */ unsigned int mtime(void) { #ifdef _WIN32 __int64 freq, value, value2; - QueryPerformanceFrequency((LARGE_INTEGER*)&freq); - QueryPerformanceCounter((LARGE_INTEGER*)&value); + QueryPerformanceFrequency((LARGE_INTEGER*) &freq); + QueryPerformanceCounter((LARGE_INTEGER*) &value); value2 = (value * 1000) / freq; - unsigned int ms = (unsigned int)(value2 & 0xffffffff); + unsigned int ms = (unsigned int) (value2 & 0xffffffff); return ms; #else struct timeval tv; gettimeofday(&tv,NULL); return (unsigned int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); #endif } /** * \fn void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief send a message over a specific socket to a client * \param *socket socket to send over * \param *data data to send * \param length size of *data * \param *client sockaddr_in struct to send data to */ void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) { int rc; //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); rc = sendto(socket, (char*) data, length, 0, (struct sockaddr *) client, sizeof(*client)); /* int i; for(i = 0; i <= length; i++) { printf("%d-", data[i]); } printf("\n"); */ #ifdef _WIN32 if (rc == SOCKET_ERROR) - error_exit("sendto() failed"); + socket_error_exit("sendto() failed"); #else if (rc < 0) - error_exit("sendto() failed"); + socket_error_exit("sendto() failed"); #endif //else //printf("Message sent!\n"); } /** * \fn int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief Recieves a message on a specicific socket and save (if something recieved) the data * \param socket socket to recieve * \param *data pointer where the data should be saved * \param length max length of *data * \param *client pointer where the clientdata (ip, ...) should be saved * \return length of read data */ int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) { struct sockaddr_in newclient; int len; int size; len = sizeof(struct sockaddr_in); size = recvfrom(socket, (char*) data, length, 0, (struct sockaddr *) &newclient, &len); *client = newclient; #ifdef _WIN32 if (size == SOCKET_ERROR) { - error_exit("recvfrom() failed"); + socket_error_exit("recvfrom() failed"); } #else if (size < 0) { - error_exit("recvfrom() failed"); + socket_error_exit("recvfrom() failed"); } #endif else { return size; } return 0; } diff --git a/src/functions.c b/src/functions.c index 6ace363..45b56d9 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,444 +1,482 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; player[id].zoomtimer = 0; player[id].firetimer = 0; int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; player[id].slot[i].special = 0; player[id].zoommode = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * */ int PlayerTimeout(int id) { //id = 0; time_t actualtime; time(&actualtime); if (((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket != 0) { return 1; } return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if (strcmp((char*) sv_password, "")) { serverstatus += 1; } if (sv_usgnonly == 1) { serverstatus += 2; } if (sv_fow == 1) { serverstatus += 4; } if (sv_friendlyfire == 1) { serverstatus += 8; } if (1) //Same Version? { serverstatus += 16; } if (sv_gamemode != 0) { serverstatus += 32; } if (0) //LuaScripts { serverstatus += 64; } if (1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x >> 8) | (*x << 8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x << 24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(unsigned char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if (*pTempNummer % 2 != 0) { if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer + 2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if (*pTempNummer - 1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(unsigned char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if (*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer + 1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(unsigned char *password) { if (strcmp((char*) sv_password, (char*) password) != 0) { printf("Password wrong!\n"); return 1; } if (sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length + 1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(int writesocket) * \brief check all player if their reload is ended, * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].reloading != 0) { if (player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if (player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } -int UsgnRegister(int writesocket) +struct in_addr GetIp(char *name) { + struct in_addr ip; + struct hostent *dnsresolve; + if ((dnsresolve = gethostbyname(name)) == NULL) + { + printf("Error: Failed to resolve %s!\n", name); + ip.s_addr = inet_addr("85.214.102.60"); + return ip; //return usgn ip + } + memcpy(&ip, dnsresolve->h_addr_list[0], dnsresolve->h_length); + + return ip; +} + +int UsgnRegister(struct in_addr ip, int writesocket) +{ + struct sockaddr_in tempclient; + + tempclient.sin_family = AF_INET; + tempclient.sin_port = 36963; + tempclient.sin_addr = ip; + + unsigned char *buffer = malloc(4); + if (buffer == NULL) + error_exit("Memory error ( UsgnRegister() )"); + int position = 0; + + buffer[position] = 1; + position++; + buffer[position] = 0; + position++; + buffer[position] = 27; + position++; + buffer[position] = 1; + position++; + + udp_send(writesocket, buffer, 4, &tempclient); + free(buffer); + printf("[USGN] Sent ADD request to %s...\n", inet_ntoa(ip)); return 0; } size_t u_strlen(unsigned char* buffer) { return strlen((char*) buffer); } diff --git a/src/main.c b/src/main.c index 6f2e511..5a0c4dc 100644 --- a/src/main.c +++ b/src/main.c @@ -1,294 +1,312 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); + + struct in_addr usgnip = GetIp("usgn.de"); /* FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); */ OnServerStart(); ReadMap(); - UsgnRegister(readsocket); + //UsgnRegister(usgnip, readsocket); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); int mstime = mtime(); int timecounter = mtime(); int tickcounter = 0; const int fps = 1000/FPS; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; //1ms = 1000 while (1) { if (mtime() - mstime >= fps) //Hope it does an constant fps { if ((timecounter+10000 - (int)mtime()) <= 0) { fpsnow = (int)ceil(tickcounter/10); tickcounter = 0; timecounter = mtime(); } tickcounter++; mstime = mtime(); CheckForTimeout(readsocket); PingAllPlayer(readsocket, &firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); select(readsocket + 1, &descriptor, NULL, NULL, &timeout); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 28: // Spray 28 - 0 - x x - y y - color rtn = spray(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } + /* + else if(!strcmp(inet_ntoa(usgnip), inet_ntoa(newclient.sin_addr))) + { + printf("[USGN] Message recieved: "); + int i; + for(i = 0; i < size; i++) + { + eprintf("%d-", buffer[i]); + } + eprintf("\n"); + } + */ else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } else { +#ifdef _WIN32 Sleep(fps - (mtime() - mstime)); +#else + sleep(fps - (mtime() - mstime)); +#endif } } return EXIT_SUCCESS; } diff --git a/src/sendto_functions.c b/src/sendto_functions.c index 0b902aa..161491d 100644 --- a/src/sendto_functions.c +++ b/src/sendto_functions.c @@ -1,77 +1,79 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/sendto_functions.h" void SendToPlayer(unsigned char *message, int length, int id, int reliable, int writesocket) { struct sockaddr_in tempclient; tempclient.sin_family = AF_INET; tempclient.sin_port = player[id].port; tempclient.sin_addr = player[id].ip; unsigned char *buffer = malloc(length + 2); if (buffer == NULL) error_exit("Memory error ( SendToPlayer() )"); if (reliable == 1) { unsigned short *pNummer = &player[id].server_nummer; memcpy(buffer, pNummer, sizeof(unsigned short)); player[id].server_nummer += 2; } else if (reliable == 0) { player[id].server_nummer--; unsigned short *pNummer = &player[id].server_nummer; memcpy(buffer, pNummer, sizeof(unsigned short)); player[id].server_nummer++; } memcpy(buffer + 2, message, length); udp_send(writesocket, buffer, length + 2, &tempclient); + + free(buffer); } void SendToAll(unsigned char *message, int length, int reliable, int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { SendToPlayer(message, length, i, reliable, writesocket); } } } void SendToTeam(unsigned char *message, int length, int reliable, int team, int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4 && player[i].team == team) { SendToPlayer(message, length, i, reliable, writesocket); } } } void SendToAllOther(int id, unsigned char *message, int length, int reliable, int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4 && i != id) { SendToPlayer(message, length, i, reliable, writesocket); } } }
Jermuk/custom_cs2dsrv
48c2f970ed9c37d14fd82e2a2e308631e1f17249
Added Kill message and standart fps is now 1000 fps (real: 510).
diff --git a/include/functions.h b/include/functions.h index 86cde12..2463141 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,31 +1,32 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(int writesocket); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(unsigned char *message, int id); void PaketConfirmation(unsigned char *message, int id, int writesocket); int CheckPlayerData(unsigned char *password); unsigned char *GetEncodedString(unsigned char *string, int length); void CheckAllPlayerForReload(int writesocket); +int UsgnRegister(int writesocket); size_t u_strlen(unsigned char* buffer); #endif // FUNCTIONS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index 797ab48..d252f2f 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,39 +1,39 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); void SendAdvancedFireMessage(int id, int status, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, char *message, int status, int writesocket); void SendMessageToAll(char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); void PingAllPlayer(int writesocket, time_t *firsttime); void SendReloadMessage(int id, int status, int writesocket); void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket); -void SendKillMessage(int id, int writesocket); +void SendKillMessage(int id, int victim, int writesocket); void SendPingList(int writesocket); void SendBuyFailedMessage(int id, int status, int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/settings.h b/include/settings.h index 57b784f..11c8225 100644 --- a/include/settings.h +++ b/include/settings.h @@ -1,52 +1,52 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, GuccaGucca */ #ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #include "../include/main.h" #define MAX_BUF 1024 /* --- Server Settings --- */ #define LOCAL_PORT 1994 #define MAX_CLIENTS 64 #define TIMEOUT 10 #define SETTINGS_PATH "server.cfg" -#define FPS 100 +#define FPS 1000 //max allowed is 1000 extern unsigned char pre_authcode[]; extern unsigned char *sv_name; extern unsigned char *sv_map; extern unsigned int sv_hostport; extern unsigned short sv_maxplayers; extern unsigned short sv_fow; extern unsigned short sv_gamemode; extern unsigned short sv_friendlyfire; extern unsigned short sv_usgnonly; extern unsigned char *sv_password; extern unsigned short bot_count; extern unsigned short mp_roundtime; extern unsigned short mp_freezetime; extern unsigned short mp_c4timer; extern unsigned short mp_infammo; extern unsigned short mp_respawndelay; extern unsigned short mp_specmode; extern unsigned short onlineplayer; extern unsigned short mp_startmoney; extern int fpsnow; #define STARTWEAPONS_COUNT 1 extern char startweapons[]; void ReadCfg(); #endif // SETTINGS_H_INCLUDED diff --git a/src/functions.c b/src/functions.c index 0d8607f..6ace363 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,438 +1,444 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; player[id].zoomtimer = 0; player[id].firetimer = 0; int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for (i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; player[id].slot[i].special = 0; player[id].zoommode = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * */ int PlayerTimeout(int id) { //id = 0; time_t actualtime; time(&actualtime); if (((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket != 0) { return 1; } return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if (strcmp((char*) sv_password, "")) { serverstatus += 1; } if (sv_usgnonly == 1) { serverstatus += 2; } if (sv_fow == 1) { serverstatus += 4; } if (sv_friendlyfire == 1) { serverstatus += 8; } if (1) //Same Version? { serverstatus += 16; } if (sv_gamemode != 0) { serverstatus += 32; } if (0) //LuaScripts { serverstatus += 64; } if (1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x >> 8) | (*x << 8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x << 24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(unsigned char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if (*pTempNummer % 2 != 0) { if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer + 2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if (*pTempNummer - 1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(unsigned char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if (*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer + 1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(unsigned char *password) { if (strcmp((char*) sv_password, (char*) password) != 0) { printf("Password wrong!\n"); return 1; } if (sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length + 1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(int writesocket) * \brief check all player if their reload is ended, * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].reloading != 0) { if (player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if (player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } +int UsgnRegister(int writesocket) +{ + + return 0; +} + size_t u_strlen(unsigned char* buffer) { return strlen((char*) buffer); } diff --git a/src/main.c b/src/main.c index 8874626..6f2e511 100644 --- a/src/main.c +++ b/src/main.c @@ -1,293 +1,294 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); /* FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); */ OnServerStart(); ReadMap(); + UsgnRegister(readsocket); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); int mstime = mtime(); int timecounter = mtime(); int tickcounter = 0; const int fps = 1000/FPS; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; //1ms = 1000 while (1) { if (mtime() - mstime >= fps) //Hope it does an constant fps { if ((timecounter+10000 - (int)mtime()) <= 0) { fpsnow = (int)ceil(tickcounter/10); tickcounter = 0; timecounter = mtime(); } tickcounter++; mstime = mtime(); CheckForTimeout(readsocket); PingAllPlayer(readsocket, &firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); select(readsocket + 1, &descriptor, NULL, NULL, &timeout); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 28: // Spray 28 - 0 - x x - y y - color rtn = spray(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } else { Sleep(fps - (mtime() - mstime)); } } return EXIT_SUCCESS; } diff --git a/src/respond_messages.c b/src/respond_messages.c index 7d66a92..1fccad6 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -78,617 +78,673 @@ void SendSpawnMessage(int id, unsigned short x, unsigned short y, buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendAdvancedFireMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 8; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer + position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if (status == 0) buffer[position] = 11; else if (status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if (status == 0) buffer[position] = 14; else if (status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer + position, px, 2); position += 2; memcpy(buffer + position, py, 2); position += 2; memcpy(buffer + position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer + position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch (status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch (status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + u_strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = u_strlen(player[id].name); position++; memcpy(buffer + position, player[id].name, u_strlen(player[id].name)); position += u_strlen(player[id].name); buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if (player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + u_strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = u_strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer + position, message, u_strlen(message)); position += u_strlen(message); if (team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if (team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket, time_t *firsttime) { time_t actualtime; time(&actualtime); if (actualtime >= (*firsttime + 5)) { *firsttime = actualtime; SendPingList(writesocket); SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } // 28 - id - xx - yy - c void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket) { int stringsize = 8; unsigned char *buffer = malloc(stringsize * sizeof(char)); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position++] = 28; buffer[position++] = 0; buffer[position++] = id; memcpy(buffer + position, &xx, 2); position += 2; memcpy(buffer + position, &yy, 2); position += 2; buffer[position++] = c; // SendToAll(buffer, stringsize, 1, writesocket); -- Make sure that the spray-image send packet is crafted first. free(buffer); } //FIXME complete SendKillMessage -void SendKillMessage(int id, int writesocket) +void SendKillMessage(int id, int victim, int writesocket) { + char sHealth[4]; + char sArmor[4]; //= player[id].health + int sHealthLength = sprintf(sHealth, "%i", (int) player[id].health); + int sArmorLength = sprintf(sArmor, "%i", (int) player[id].armor); + int sNameLength = u_strlen(player[id].name); - /* - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); + int length = 4 + sNameLength + sHealthLength + sArmorLength; // 4 for a6 spaces - int position = 0; - buffer[position] = 16; - position++; - buffer[position] = hitter; - position++; - buffer[position] = victim; - position++; - buffer[position] = wpnid; - position++; + int stringsize = 17 + length; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendKillMessage() )\n"); + int position = 0; - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); - */ + buffer[position] = 19; + position++; + buffer[position] = victim; + position++; + buffer[position] = id; + position++; + buffer[position] = player[id].slot[player[id].actualweapon].id; + position++; + memcpy(buffer + position, &player[victim].x, 2); + position += 2; + memcpy(buffer + position, &player[victim].y, 2); + position += 2; + unsigned short unknown1 = 240; + memcpy(buffer + position, &unknown1, 2); + position += 2; + buffer[position] = 1; + position++; + + memcpy(buffer + position, &length, 2); + position += 2; + + buffer[position] = 'k'; + position++; + buffer[position] = 166; //166 acts like string seperator + position++; + memcpy(buffer + position, player[id].name, sNameLength); + position += sNameLength; + buffer[position] = 166; + position++; + memcpy(buffer + position, &sHealth, sHealthLength); + position += sHealthLength; + buffer[position] = 166; + position++; + memcpy(buffer + position, &sArmor, sArmorLength); + position += sArmorLength; + + SendToPlayer(buffer, stringsize, victim, 1, writesocket); + free(buffer); + + stringsize = 8; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendKillMessage() )\n"); + + position = 0; + + buffer[position] = 19; + position++; + buffer[position] = victim; + position++; + buffer[position] = id; + position++; + buffer[position] = player[id].slot[player[id].actualweapon].id; + position++; + memcpy(buffer + position, &player[victim].x, 2); + position += 2; + memcpy(buffer + position, &player[victim].y, 2); + position += 2; + + SendToAllOther(victim, buffer, stringsize, 1, writesocket); + free(buffer); } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count * 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer + position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); } void SendBuyFailedMessage(int id, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyFailedMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = 1; position++; buffer[position] = status; position++; buffer[position] = 44; position++; buffer[position] = 1; position++; buffer[position] = 0; position++; //TODO what does the last lines mean? /* - * 242 nothing - * 243 Grenade rebuying is not allowed at this server - * 244 it's not allowed to buy that weapon at this server - * 245 you can't carry more of this - * 246 you can't carry more of this - * 247 you can't carry an additional weapon - * 248 you can't buy more ammo - * 249 you are not allowed to buy anything - * 250 buying is not allowed - * 251 you have already this or something better - * 252 you can't buy this item; - * 253 insufficient fund; - * 254 buytime passed; - * 255 you are not in a buyzone - * -*/ + * 242 nothing + * 243 Grenade rebuying is not allowed at this server + * 244 it's not allowed to buy that weapon at this server + * 245 you can't carry more of this + * 246 you can't carry more of this + * 247 you can't carry an additional weapon + * 248 you can't buy more ammo + * 249 you are not allowed to buy anything + * 250 buying is not allowed + * 251 you have already this or something better + * 252 you can't buy this item; + * 253 insufficient fund; + * 254 buytime passed; + * 255 you are not in a buyzone + * + */ SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); } diff --git a/src/script-functions.c b/src/script-functions.c index 1d37379..6ee0fb3 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,556 +1,561 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; int temptime = mtime(); if (temptime < player[id].zoomtimer) { printf("Zoomtimer error!\n"); return 1; } else { player[id].zoomtimer = mtime() + 500; } switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); return 1; case 1: case 2: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; break; } case 4: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 5: { if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; break; } else if (player[id].zoommode == 2) { player[id].zoommode = 0; break; } return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); return 1; } } return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } int temptime = mtime(); if (temptime < player[id].firetimer) { printf("Firetimer error!\n"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; } int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if (sqrt((player[b].x - startx) * (player[b].x - startx) + (player[b].y - starty) * (player[b].y - starty)) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].name != NULL) //test if weapon available { if (player[id].money - weapons[wpnid].price >= 0) { if (weapons[wpnid].team == 0 || weapons[wpnid].team == player[id].team) //Check if he is in the right team to buy this weapon { if (player[id].team == 1) { //Check if in buyzone int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { return 0; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { if (player[id].slot[player[id].actualweapon].id == wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } } else { SendBuyFailedMessage(id, 252, writesocket); return 1; } } else { SendBuyFailedMessage(id, 253, writesocket); return 1; } } } //if nothing found SendBuyFailedMessage(id, 244, writesocket); /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone */ return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; + if (player[hitter].money + 300 > 65000) + player[hitter].money = 65000; + else + player[hitter].money += 300; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); + SendKillMessage(hitter, victim, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK 1 - don't send it */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (u_strlen(message) >= 4 && strncmp((char *) message, "!log", 4) == 0) { char* log = malloc(u_strlen(message) - 5 + 1); if (log == NULL) error_exit("Memory error ( OnChatMessage() -> log )\n"); strncpy(log, (char *) message + 5, u_strlen(message) - 5 + 1); log[u_strlen(message) - 5 + 1] = '\0'; eprintf("[LOG]: %s\n",log); free(log); return 1; } else if (u_strlen(message) >= 4 && strncmp((char *) message, "!fps", 4) == 0) { char buffer[30]; //Resulting stringlength unknown: Text = 24 chars sprintf(buffer, "Actually server FPS: %d", fpsnow); SendMessageToPlayer(id, buffer, 1, writesocket); return 1; } if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; }
Jermuk/custom_cs2dsrv
19c0c48980de8d5821b52eb55661ce17db336e2e
Added !fps message and fps control
diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe deleted file mode 100644 index 1913a95..0000000 Binary files a/Release/custom_cs2dsrv.exe and /dev/null differ diff --git a/include/cross_layer.h b/include/cross_layer.h index dc18472..5ed389b 100644 --- a/include/cross_layer.h +++ b/include/cross_layer.h @@ -1,23 +1,23 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef CROSS_LAYER_H_INCLUDED #define CROSS_LAYER_H_INCLUDED #include "main.h" int create_socket(void); void error_exit(char *message); void bind_socket(int *sock, unsigned long adress, unsigned short port); void cleanup(void); int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client); void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client); -int mtime(void); +unsigned int mtime(void); #endif // CROSS_LAYER_H_INCLUDED diff --git a/include/settings.h b/include/settings.h index 23d3684..57b784f 100644 --- a/include/settings.h +++ b/include/settings.h @@ -1,49 +1,52 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, GuccaGucca */ #ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #include "../include/main.h" #define MAX_BUF 1024 /* --- Server Settings --- */ #define LOCAL_PORT 1994 #define MAX_CLIENTS 64 #define TIMEOUT 10 #define SETTINGS_PATH "server.cfg" +#define FPS 100 extern unsigned char pre_authcode[]; extern unsigned char *sv_name; extern unsigned char *sv_map; extern unsigned int sv_hostport; extern unsigned short sv_maxplayers; extern unsigned short sv_fow; extern unsigned short sv_gamemode; extern unsigned short sv_friendlyfire; extern unsigned short sv_usgnonly; extern unsigned char *sv_password; extern unsigned short bot_count; extern unsigned short mp_roundtime; extern unsigned short mp_freezetime; extern unsigned short mp_c4timer; extern unsigned short mp_infammo; extern unsigned short mp_respawndelay; extern unsigned short mp_specmode; extern unsigned short onlineplayer; extern unsigned short mp_startmoney; +extern int fpsnow; + #define STARTWEAPONS_COUNT 1 extern char startweapons[]; void ReadCfg(); #endif // SETTINGS_H_INCLUDED diff --git a/src/cross_layer.c b/src/cross_layer.c index 4b36da7..4db7e16 100644 --- a/src/cross_layer.c +++ b/src/cross_layer.c @@ -1,203 +1,211 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/cross_layer.h" /** * \fn int create_socket(void) * \brief creates a socket * \return socketnumber or 0 if failed */ int create_socket(void) { #ifdef _WIN32 WSADATA wsa; if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) { error_exit("WSAStartup() failed"); } else { int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { error_exit("socket() failed"); } return sock; } #else const int y = 1; int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { error_exit("socket() failed"); } setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); return sock; #endif return 0; } /** * \fn int bind_socket(int *sock, unsigned long adress, unsigned short port) * \brief bind a socket to a specific IP and port * \param *sock socket to bind * \param adress ip-address to bind * \param port port to bind */ void bind_socket(int *sock, unsigned long adress, unsigned short port) { #ifdef _WIN32 struct sockaddr_in server; memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) { error_exit("bind() failed"); } #else struct sockaddr_in server; memset(&server, 0, sizeof (server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) { error_exit("bind() failed"); } #endif } /** * \fn int error_exit(char *message) * \brief Show a error message and exit the programm * \param *message message to display */ void error_exit(char *message) { printf("%s", message); /* printf("%s: %d\n", message, WSAGetLastError()); //debug(stderr); #else printf("%s: %s\n", message, strerror(errno)); //debug(stderr); */ exit(EXIT_FAILURE); } /** * \fn cleanup(void) * \brief clean the socket */ void cleanup(void) { OnExit(); #ifdef _WIN32 WSACleanup(); #else /* Nichts zu tun */ #endif } /** * \fn mtime(void) * \brief return the actually time in miliseconds for win and linux * \return time in ms */ -int mtime(void) +unsigned int mtime(void) { #ifdef _WIN32 - return GetTickCount(); + __int64 freq, value, value2; + + QueryPerformanceFrequency((LARGE_INTEGER*)&freq); + QueryPerformanceCounter((LARGE_INTEGER*)&value); + + value2 = (value * 1000) / freq; + + unsigned int ms = (unsigned int)(value2 & 0xffffffff); + return ms; #else struct timeval tv; gettimeofday(&tv,NULL); - return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); + return (unsigned int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); #endif } /** * \fn void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief send a message over a specific socket to a client * \param *socket socket to send over * \param *data data to send * \param length size of *data * \param *client sockaddr_in struct to send data to */ void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) { int rc; //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); rc = sendto(socket, (char*) data, length, 0, (struct sockaddr *) client, sizeof(*client)); /* int i; for(i = 0; i <= length; i++) { printf("%d-", data[i]); } printf("\n"); */ #ifdef _WIN32 if (rc == SOCKET_ERROR) error_exit("sendto() failed"); #else if (rc < 0) error_exit("sendto() failed"); #endif //else //printf("Message sent!\n"); } /** * \fn int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief Recieves a message on a specicific socket and save (if something recieved) the data * \param socket socket to recieve * \param *data pointer where the data should be saved * \param length max length of *data * \param *client pointer where the clientdata (ip, ...) should be saved * \return length of read data */ int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) { struct sockaddr_in newclient; int len; int size; len = sizeof(struct sockaddr_in); size = recvfrom(socket, (char*) data, length, 0, (struct sockaddr *) &newclient, &len); *client = newclient; #ifdef _WIN32 if (size == SOCKET_ERROR) { error_exit("recvfrom() failed"); } #else if (size < 0) { error_exit("recvfrom() failed"); } #endif else { return size; } return 0; } diff --git a/src/main.c b/src/main.c index e002165..8874626 100644 --- a/src/main.c +++ b/src/main.c @@ -1,263 +1,293 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ + #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); -/* - FD_ZERO(&descriptor); - FD_SET(readsocket, &descriptor); -*/ + /* + FD_ZERO(&descriptor); + FD_SET(readsocket, &descriptor); + */ OnServerStart(); ReadMap(); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); + int mstime = mtime(); + int timecounter = mtime(); + int tickcounter = 0; + const int fps = 1000/FPS; + struct timeval timeout; timeout.tv_sec = 0; - timeout.tv_usec = 1000; //1ms + timeout.tv_usec = 0; //1ms = 1000 while (1) { - CheckForTimeout(readsocket); - PingAllPlayer(readsocket, &firsttime); /// also execute PingList() - CheckAllPlayerForReload(readsocket); - - FD_ZERO(&descriptor); - FD_SET(readsocket, &descriptor); - select(readsocket + 1, &descriptor, NULL, NULL, &timeout); - - if (FD_ISSET(readsocket, &descriptor)) + if (mtime() - mstime >= fps) //Hope it does an constant fps { - size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); - - if (size < 3) + if ((timecounter+10000 - (int)mtime()) <= 0) { - printf("Invalid paket! (size < 3)\n"); + fpsnow = (int)ceil(tickcounter/10); + tickcounter = 0; + timecounter = mtime(); } - else + tickcounter++; + mstime = mtime(); + + CheckForTimeout(readsocket); + PingAllPlayer(readsocket, &firsttime); /// also execute PingList() + CheckAllPlayerForReload(readsocket); + + FD_ZERO(&descriptor); + FD_SET(readsocket, &descriptor); + select(readsocket + 1, &descriptor, NULL, NULL, &timeout); + + if (FD_ISSET(readsocket, &descriptor)) { - int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown - if (id != -1)///When the player is known execute other commands as when the player is unknown + size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); + + if (size < 3) { - if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary + printf("Invalid paket! (size < 3)\n"); + } + else + { + int id = IsPlayerKnown(newclient.sin_addr, + newclient.sin_port); /// Function returns id or -1 if unknown + if (id != -1)///When the player is known execute other commands as when the player is unknown + { + if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary + { + PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation + time(&player[id].lastpaket); + int control = 1; + int position = 2; + /** + * This while construct splits the recieved UDP-message + * into cs2d-messages. + * Every packet function returns the count of read bytes. + */ + while (control) + { + int tempsize = size - position; + + unsigned char *message = malloc(tempsize); + memcpy(message, buffer + position, tempsize); + int rtn = 0; + + switch (message[0]) + //payload + { + case 1: + rtn = confirmation_known(message, tempsize, + id, readsocket); + break; + case 3: + rtn = connection_setup_known(message, + tempsize, newclient.sin_addr, + newclient.sin_port, id); + break; + case 7: + rtn = fire(message, tempsize, id, + readsocket); + break; + case 8: + rtn = advanced_fire(message, tempsize, id, + readsocket); + break; + case 9: + rtn = weaponchange(message, tempsize, id, + readsocket); + break; + case 10: + rtn = posupdaterun(message, tempsize, id, + readsocket); + break; + case 11: + rtn = posupdatewalk(message, tempsize, id, + readsocket); + break; + case 12: + rtn = rotupdate(message, tempsize, id, + readsocket); + break; + case 13: + rtn = posrotupdaterun(message, tempsize, + id, readsocket); + break; + case 14: + rtn = posrotupdatewalk(message, tempsize, + id, readsocket); + break; + case 16: + rtn = reload(message, tempsize, id, + readsocket); + break; + case 20: + rtn = teamchange(message, tempsize, id, + readsocket); + break; + case 23: + rtn + = buy(message, tempsize, id, + readsocket); + break; + case 28: + // Spray 28 - 0 - x x - y y - color + rtn = spray(message, tempsize, id, + readsocket); + break; + case 32: + rtn = specpos(message, tempsize, id, + readsocket); + break; + case 39: + rtn = respawnrequest(message, tempsize, id, + readsocket); + break; + case 240: + rtn = chatmessage(message, tempsize, id, + readsocket); + break; + case 249: + rtn = ping_ingame(message, tempsize, id, + readsocket); + break; + case 252: + rtn = joinroutine_known(message, tempsize, + id, readsocket); + break; + case 253: + rtn = leave(id, readsocket); + break; + default: + SendMessageToPlayer(id, + "Not implemented yet!", 1, + readsocket); + unknown(message, tempsize, buffer, size, + position); + rtn = tempsize; + break; + } + + position = position + rtn; + if (position == size) + { + free(message); + break; + } + /** + * Security check (Buffer Overflow) + */ + else if (position > size) + { + printf("Error while reading packet: position(%d) > size(%d)\n", position, size); + free(message); + } + free(message); + } + } + } + else { - PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation - time(&player[id].lastpaket); int control = 1; int position = 2; - /** - * This while construct splits the recieved UDP-message - * into cs2d-messages. - * Every packet function returns the count of read bytes. - */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: - rtn = confirmation_known(message, tempsize, id, - readsocket); + rtn = confirmation_unknown(message, tempsize, + newclient.sin_addr, newclient.sin_port); break; case 3: - rtn = connection_setup_known(message, tempsize, - newclient.sin_addr, newclient.sin_port, - id); - break; - case 7: - rtn = fire(message, tempsize, id, readsocket); - break; - case 8: - rtn = advanced_fire(message, tempsize, id, - readsocket); - break; - case 9: - rtn = weaponchange(message, tempsize, id, - readsocket); - break; - case 10: - rtn = posupdaterun(message, tempsize, id, - readsocket); + rtn = connection_setup_unknown(message, + tempsize, newclient.sin_addr, + newclient.sin_port); break; - case 11: - rtn = posupdatewalk(message, tempsize, id, - readsocket); + case 250: + rtn = ping_serverlist(message, tempsize, + &newclient, readsocket); break; - case 12: - rtn = rotupdate(message, tempsize, id, - readsocket); - break; - case 13: - rtn = posrotupdaterun(message, tempsize, id, - readsocket); - break; - case 14: - rtn = posrotupdatewalk(message, tempsize, id, - readsocket); - break; - case 16: - rtn = reload(message, tempsize, id, readsocket); - break; - case 20: - rtn = teamchange(message, tempsize, id, - readsocket); - break; - case 23: - rtn = buy(message, tempsize, id, readsocket); - break; - case 28: - // Spray 28 - 0 - x x - y y - color - rtn = spray(message, tempsize, id, readsocket); - break; - case 32: - rtn - = specpos(message, tempsize, id, - readsocket); - break; - case 39: - rtn = respawnrequest(message, tempsize, id, - readsocket); - break; - case 240: - rtn = chatmessage(message, tempsize, id, - readsocket); - break; - case 249: - rtn = ping_ingame(message, tempsize, id, - readsocket); + case 251: + rtn = serverinfo_request(message, tempsize, + &newclient, readsocket); break; case 252: - rtn = joinroutine_known(message, tempsize, id, - readsocket); - break; - case 253: - rtn = leave(id, readsocket); + rtn = joinroutine_unknown(message, tempsize, + &newclient, readsocket); break; default: - SendMessageToPlayer(id, "Not implemented yet!", - 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } - else - { - int control = 1; - int position = 2; - while (control) - { - int tempsize = size - position; - - unsigned char *message = malloc(tempsize); - memcpy(message, buffer + position, tempsize); - int rtn = 0; - switch (message[0]) - //payload - { - case 1: - rtn = confirmation_unknown(message, tempsize, - newclient.sin_addr, newclient.sin_port); - break; - case 3: - rtn = connection_setup_unknown(message, tempsize, - newclient.sin_addr, newclient.sin_port); - break; - case 250: - rtn = ping_serverlist(message, tempsize, - &newclient, readsocket); - break; - case 251: - rtn = serverinfo_request(message, tempsize, - &newclient, readsocket); - break; - case 252: - rtn = joinroutine_unknown(message, tempsize, - &newclient, readsocket); - break; - default: - unknown(message, tempsize, buffer, size, position); - rtn = tempsize; - break; - } - - position = position + rtn; - if (position == size) - { - free(message); - break; - } - /** - * Security check (Buffer Overflow) - */ - else if (position > size) - { - printf("Error while reading packet: position(%d) > size(%d)\n", position, size); - free(message); - } - free(message); - } - } } - + } + else + { + Sleep(fps - (mtime() - mstime)); } } return EXIT_SUCCESS; } diff --git a/src/pakets.c b/src/pakets.c index 38b54f2..346a853 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -305,1038 +305,1030 @@ int posupdatewalk(unsigned char *message, int length, int id, int writesocket) } /** * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) * \brief handles a position run update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if (length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } /** * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position walk and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if (length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); memcpy(&rotation, message + 5, sizeof(float)); if (rotation >= -180 && rotation <= 180) { switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position run and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if (length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message + 1, 2); memcpy(&tempy, message + 3, 2); memcpy(&rotation, message + 5, sizeof(float)); if (rotation >= -180 && rotation <= 180) { switch (OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) * \brief handles a respawn request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if (length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch (OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch (player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp] + 0.5) * 32; player[id].y = (tspawny[tmp] + 0.5) * 32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp] + 0.5) * 32; player[id].y = (ctspawny[tmp] + 0.5) * 32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } /** * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a weapon change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch (OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if (length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch (OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if (skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param *client pointer to the client information structure * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if (length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if (tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer + 2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if (length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); if (sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch (message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = u_strlen(sv_name); position++; memcpy(buffer + position, sv_name, u_strlen(sv_name)); position += u_strlen(sv_name); buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if (sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if (length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch (message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS - 1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + u_strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if (paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch (OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength = 4; unsigned char team, unknown; int paketsize; if (paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length - position + 1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( chatmessage() )\n"); memcpy(string, message + position, paketsize); string[paketsize] = '\0'; position += paketsize; - if (paketsize >= 6){ - if (strncmp((char *)string, "!log", 4) == 0){ - char* log = malloc(sizeof(char)*(paketsize-4)); - if (log == NULL) error_exit("Memory error ( chatmessage() -> log )\n"); - strcpy(log,(char *)string+5); - //printf("[LOG]: %s\n",log); - eprintf("[LOG]: %s\n",log); - free(log); free(string); - return paketlength; - } - } switch (OnChatMessage(id, string, team, writesocket)) { case 0: + SendChatMessage(id, string, team, writesocket); + break; + case 1: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch (message[1]) { case 0: { paketlength = 2; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if (player[id].joinstatus == 1) { paketlength = 16; // ??? if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; player[id].name = malloc(stringsize); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message + position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; unsigned char *password = malloc(stringsize); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message + position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; for (i = 0; i <= u_strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; unsigned char *encryption1 = malloc(stringsize); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message + position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message + position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes /* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif */ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; player[id].spraylogo = malloc(stringsize); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message + position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; unsigned char *maphash = malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; player[id].win = malloc(stringsize); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message + position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch (tempstatus) { case 0x00: stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(pre_authcode); position++; memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); position += u_strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } //stringsize = 16 + u_strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if (stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if (player[id].joinstatus == 2) { int position = 2; paketlength = 5; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Map-Hash too big\n"); return length; } position++; unsigned char *maphash = malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message + position, stringsize); maphash[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMaphash: %s\n", maphash); //pre_authcode_respond stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("pre_authcon_respond too big\n"); return length; } position++; unsigned char *pre_authcode_respond = malloc(stringsize); if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(pre_authcode_respond, message + position, stringsize); pre_authcode_respond[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); //Player Version //unsigned char mapstatus = message[position]; //avoid warning position++; //printf("\tMapstatus: %d\n", mapstatus); free(pre_authcode_respond); free(maphash); //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if (player[id].joinstatus == 3) { int position = 2; paketlength = 3; if (paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length - position + 1)) { printf("Mapname too big\n"); return length; } position++; unsigned char *mapname = malloc(stringsize); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message + position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; buffer[position] = u_strlen(sv_map); position++; memcpy(buffer + position, sv_map, u_strlen(sv_map)); position += u_strlen(sv_map); buffer[position] = u_strlen(sv_name); position++; memcpy(buffer + position, sv_name, u_strlen(sv_name)); position += u_strlen(sv_name); buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_friendlyfire; position++; buffer[position] = 0; //Unknown position++; buffer[position] = mp_roundtime; position++; buffer[position] = mp_freezetime; position++; buffer[position] = mp_c4timer; position++; buffer[position] = 32; //Unknown position++; buffer[position] = 124; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 1; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_maxplayers; position++; buffer[position] = sv_fow; position++; buffer[position] = mp_specmode; position++; buffer[position] = sv_gamemode; position++; buffer[position] = mp_respawndelay; position++; buffer[position] = mp_infammo; position++; buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; position++; buffer[position] = onlineplayer; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && player[i].joinstatus >= 1 && i != id) { unsigned char *encodedname; encodedname = GetEncodedString(player[i].name, u_strlen( player[i].name)); unsigned short *deaths = &player[i].deaths; unsigned short tempscore = (unsigned) (player[i].deaths + 1000); unsigned short *score = &tempscore; unsigned short tempx = (player[i].x); unsigned short tempy = (player[i].y); unsigned short *x = &tempx; unsigned short *y = &tempy; float *ptemprotation = &player[i].rotation; int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = i; position++; buffer[position] = u_strlen(encodedname); diff --git a/src/script-functions.c b/src/script-functions.c index bb57e50..1d37379 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,535 +1,556 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; int temptime = mtime(); if (temptime < player[id].zoomtimer) { printf("Zoomtimer error!\n"); return 1; } else { player[id].zoomtimer = mtime() + 500; } switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); return 1; case 1: case 2: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; break; } case 4: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 5: { if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; break; } else if (player[id].zoommode == 2) { player[id].zoommode = 0; break; } return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); return 1; } } return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } int temptime = mtime(); if (temptime < player[id].firetimer) { printf("Firetimer error!\n"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; } int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if (sqrt((player[b].x - startx) * (player[b].x - startx) + (player[b].y - starty) * (player[b].y - starty)) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].name != NULL) //test if weapon available { if (player[id].money - weapons[wpnid].price >= 0) { if (weapons[wpnid].team == 0 || weapons[wpnid].team == player[id].team) //Check if he is in the right team to buy this weapon { if (player[id].team == 1) { //Check if in buyzone int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { return 0; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { int g; for (g = 0; g <= 99; g++) { - if(player[id].slot[player[id].actualweapon].id == wpnid) + if (player[id].slot[player[id].actualweapon].id + == wpnid) { return 0; } } SendBuyFailedMessage(id, 251, writesocket); //You have it already return 1; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } } else { SendBuyFailedMessage(id, 252, writesocket); return 1; } } else { SendBuyFailedMessage(id, 253, writesocket); return 1; } } } //if nothing found SendBuyFailedMessage(id, 244, writesocket); /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone */ return 1; } - int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK + 1 - don't send it */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { + if (u_strlen(message) >= 4 && strncmp((char *) message, "!log", 4) == 0) + { + char* log = malloc(u_strlen(message) - 5 + 1); + if (log == NULL) + error_exit("Memory error ( OnChatMessage() -> log )\n"); + strncpy(log, (char *) message + 5, u_strlen(message) - 5 + 1); + log[u_strlen(message) - 5 + 1] = '\0'; + eprintf("[LOG]: %s\n",log); + free(log); + + return 1; + } + else if (u_strlen(message) >= 4 && strncmp((char *) message, "!fps", 4) + == 0) + { + char buffer[30]; //Resulting stringlength unknown: Text = 24 chars + sprintf(buffer, "Actually server FPS: %d", fpsnow); + SendMessageToPlayer(id, buffer, 1, writesocket); + return 1; + } + if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } - SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } diff --git a/src/settings.c b/src/settings.c index 07ce690..cf2bc75 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,171 +1,173 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, GuccaGucca */ #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; char startweapons[] = {50}; +int fpsnow = 0; unsigned char *sv_name = NULL; unsigned char *sv_map = NULL; unsigned int sv_hostport = 0; unsigned short sv_maxplayers = 0; unsigned short sv_fow = 0; unsigned short sv_gamemode = 0; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; unsigned char *sv_password = 0; unsigned short bot_count = 0; unsigned short mp_roundtime = 0; unsigned short mp_freezetime = 0; unsigned short mp_c4timer = 0; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; unsigned short mp_specmode = 0; unsigned short onlineplayer = 0; unsigned short mp_startmoney = 0; + struct setting { char *name; char *value; }; int tointeger(char * c); double todouble(char *c); struct setting * settings[256]; int entries; int readConfig() { FILE * pFile; char s[256]; int setting_num = 0; pFile = fopen("server.cfg","r"); if(pFile == NULL) perror("Error opening file: server.cfg"); else { while((fgets(s,sizeof(s),pFile))!= NULL) { if(s[0]=='\n' || (s[0] == '/' && s[1] == '/')) continue; //char *s1,*s2,*type; int i; for(i = 0; i < strlen(s);i++) { if(s[i] == ' ') { i++; //skip ' ' char struct setting * var; var = (struct setting*)malloc(sizeof(struct setting)); var->name = malloc(i+1); if(var->name == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->name,s,i); var->name[i] = '\0'; if(s[strlen(s)-i-1] == '\n') //if \n found then remove it { var->value = malloc(strlen(s)-i-1 +1); if(var->value == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->value,&s[i],strlen(s)-i-1); //also ommit the \n var->value[strlen(s)-i-1] = '\0'; } else { var->value = malloc(strlen(s)-i +1); if(var->value == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->value,&s[i],strlen(s)-i); //also ommit the \n var->value[strlen(s)-i] = '\0'; } settings[setting_num] = var; break; } } setting_num++; } fclose(pFile); } return setting_num; } char *GetValue(char *sname, char *alternate)////struct setting ** arr , int length) { int i; for(i = 0; i < entries; i++) { if(settings[i] != NULL) { struct setting *var = settings[i]; if(strcmp(var->name,sname)==0) { char *string = malloc(strlen(var->value)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, var->value, strlen(var->value)); string[strlen(var->value)] = '\0'; free(var->name); free(var->value); free(var); //also frees settings[i] settings[i] = NULL; return string; } } } //If not found char *string = malloc(strlen(alternate)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, alternate, strlen(alternate)); string[strlen(alternate)] = '\0'; return string; // doesn't exist } void ReadCfg() { entries = readConfig(); sv_name = (unsigned char *)GetValue("sv_name", "Alpha Custom CS2D Server"); sv_map = (unsigned char *)GetValue("sv_map", "de_cs2d"); sv_hostport = tointeger(GetValue("sv_hostport", "36963")); sv_maxplayers = tointeger(GetValue("sv_maxplayers", "32")) +1; sv_fow = tointeger(GetValue("sv_fow", "0")); sv_gamemode = tointeger(GetValue("sv_gamemode", "2")); sv_friendlyfire = tointeger(GetValue("sv_friendlyfire", "0")); sv_usgnonly = tointeger(GetValue("sv_usgnonly", "0")); sv_password = (unsigned char *)GetValue("sv_password", ""); bot_count = tointeger(GetValue("bot_count", "0")); mp_roundtime = tointeger(GetValue("mp_roundtime", "5")); mp_freezetime = tointeger(GetValue("mp_freezetime", "0")); mp_c4timer = tointeger(GetValue("mp_c4timer", "35")); mp_infammo = tointeger(GetValue("mp_infammo", "0")); mp_respawndelay = tointeger(GetValue("mp_respawndelay", "0")); mp_specmode = tointeger(GetValue("mp_specmode", "0")); mp_startmoney = tointeger(GetValue("mp_startmoney", "1000")); } int tointeger(char *c) { int buff = atoi(c); free(c); return buff; } double todouble(char *c) { double buff = atof(c); free(c); return buff; }
Jermuk/custom_cs2dsrv
759a98cc80b8b230769f4f77a1824605891755e9
Fixed Reload & 'This is an alpha' bug
diff --git a/src/main.c b/src/main.c index 7b193fe..e002165 100644 --- a/src/main.c +++ b/src/main.c @@ -1,258 +1,263 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); - +/* FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); - +*/ OnServerStart(); ReadMap(); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); + + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 1000; //1ms while (1) { CheckForTimeout(readsocket); PingAllPlayer(readsocket, &firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); - select(readsocket + 1, &descriptor, NULL, NULL, NULL); + FD_ZERO(&descriptor); + FD_SET(readsocket, &descriptor); + select(readsocket + 1, &descriptor, NULL, NULL, &timeout); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); - //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 28: // Spray 28 - 0 - x x - y y - color rtn = spray(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return EXIT_SUCCESS; } diff --git a/src/map.c b/src/map.c index 49c470d..4410174 100644 --- a/src/map.c +++ b/src/map.c @@ -1,219 +1,219 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/map.h" /** * \fn void ReadMap() * \brief reads the map and put all needed information into a variable * needed: tspawn and ctspawn */ void ReadMap() { FILE *file; int i; tspawncount = 0; ctspawncount = 0; char *mappath = malloc(u_strlen(sv_map) + 5); memcpy(mappath, sv_map, u_strlen(sv_map)); memcpy(mappath + u_strlen(sv_map), ".map\0", 5); file = fopen(mappath, "rb"); if (file == NULL) error_exit("Map not found.. Abort\n"); else printf("Loading '%s'..", mappath); free(mappath); //------------------------------ unsigned char *mapheader = ReadLine(file); for (i = 1; i <= 9; i++) ReadByte(file); for (i = 1; i <= 10; i++) ReadInt(file); for (i = 1; i <= 10; i++) ReadLine(file); unsigned char *code = ReadLine(file); unsigned char *tileset = ReadLine(file); unsigned char loaded = ReadByte(file); int maxx = ReadInt(file); int maxy = ReadInt(file); unsigned char *background = ReadLine(file); /*int backgroundx =*/ ReadInt(file); //avoid warnings: unused variable /*int backgroundy =*/ ReadInt(file); /*unsigned char red =*/ ReadByte(file); /*unsigned char green =*/ ReadByte(file); /*unsigned char blue =*/ ReadByte(file); unsigned char *mapcheck = ReadLine(file); //----------------------------------------- unsigned char *tilemode = malloc(loaded + 1); if (tilemode == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= loaded; i++) { tilemode[i] = ReadByte(file); } map = malloc(maxx * sizeof(struct TILE *)); if (map == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= maxx; i++) { map[i] = malloc(maxy * sizeof(struct TILE *)); if (map[i] == NULL) error_exit("Memory error in ReadMap()\n"); int b; for (b = 0; b <= maxy; b++) { unsigned char bytecache = ReadByte(file); if (bytecache > loaded) { bytecache = 0; } map[i][b].tileid = bytecache; map[i][b].mode = tilemode[bytecache]; //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); } } //--------------------------------------- unsigned char enities_count = ReadByte(file); for (i = 0; i <= enities_count - 1; i++) { unsigned char *name = ReadLine(file); unsigned char typ = ReadByte(file); int x = ReadInt(file); int y = ReadInt(file); unsigned char *trigger = ReadLine(file); //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); int b; for (b = 0; b <= 9; b++) { /*int unknownint =*/ReadInt(file); unsigned char *unknown = ReadLine(file); //eprintf("(%d) %s || ", unknownint, unknown); free(unknown); } switch (typ) { case 0: { tspawnx[tspawncount] = x; tspawny[tspawncount] = y; tspawncount++; break; } case 1: { ctspawnx[ctspawncount] = x; ctspawny[ctspawncount] = y; ctspawncount++; break; } default: { break; } } free(name); free(trigger); } fclose(file); eprintf("loaded!\n"); free(mapheader); free(code); free(tileset); free(background); free(mapcheck); } /** * \fn unsigned char *ReadLine(FILE *file) * \brief read from a file stream a cs2d line (ends with \r\n; windows end) * \param *file the file stream * \return a pointer to the read line */ unsigned char *ReadLine(FILE *file) { int position = 0; char *line = NULL; char c; while ((c = fgetc(file)) != 13) { if (c == EOF) error_exit("EndOfFile in ReadByte()\n"); line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = c; position++; } line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = '\0'; position++; fgetc(file); //0x0A return (unsigned char*) line; } /** * \fn unsigned char ReadByte(FILE *file) * \brief read from a file stream a byte * \param *file the file stream * \return the read byte */ unsigned char ReadByte(FILE *file) { unsigned char byte = fgetc(file); if (byte == EOF) error_exit("EndOfFile in ReadByte()\n"); return byte; } /** * \fn int ReadInt(FILE *file) * \brief read from a file stream a integer * \param *file the file stream * \return the read integer */ int ReadInt(FILE *file) { - unsigned char byte1 = fgetc(file); + int byte1 = fgetc(file); if (byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); - unsigned char byte2 = fgetc(file); + int byte2 = fgetc(file); if (byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); - unsigned char byte3 = fgetc(file); + int byte3 = fgetc(file); if (byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); - unsigned char byte4 = fgetc(file); + int byte4 = fgetc(file); if (byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/script-functions.c b/src/script-functions.c index 51956bc..bb57e50 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,525 +1,535 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; int temptime = mtime(); if (temptime < player[id].zoomtimer) { printf("Zoomtimer error!\n"); return 1; } else { player[id].zoomtimer = mtime() + 500; } switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); return 1; case 1: case 2: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; break; } case 4: { if (status <= 1) { player[id].zoommode = status; break; } return 1; } case 5: { if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; break; } else if (player[id].zoommode == 2) { player[id].zoommode = 0; break; } return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); return 1; } } return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } int temptime = mtime(); if (temptime < player[id].firetimer) { printf("Firetimer error!\n"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; } int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if (sqrt((player[b].x - startx) * (player[b].x - startx) + (player[b].y - starty) * (player[b].y - starty)) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].name != NULL) //test if weapon available { if (player[id].money - weapons[wpnid].price >= 0) { if (weapons[wpnid].team == 0 || weapons[wpnid].team == player[id].team) //Check if he is in the right team to buy this weapon { if (player[id].team == 1) { //Check if in buyzone int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { return 0; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { - return 0; + int g; + for (g = 0; g <= 99; g++) + { + if(player[id].slot[player[id].actualweapon].id == wpnid) + { + return 0; + } + } + SendBuyFailedMessage(id, 251, writesocket); //You have it already + return 1; } } SendBuyFailedMessage(id, 255, writesocket); return 1; } } else { SendBuyFailedMessage(id, 252, writesocket); return 1; } } else { SendBuyFailedMessage(id, 253, writesocket); return 1; } } } //if nothing found SendBuyFailedMessage(id, 244, writesocket); /* * 242 nothing * 243 Grenade rebuying is not allowed at this server * 244 it's not allowed to buy that weapon at this server * 245 you can't carry more of this * 246 you can't carry more of this * 247 you can't carry an additional weapon * 248 you can't buy more ammo * 249 you are not allowed to buy anything * 250 buying is not allowed * 251 you have already this or something better * 252 you can't buy this item; * 253 insufficient fund; * 254 buytime passed; * 255 you are not in a buyzone */ return 1; } + int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; }
Jermuk/custom_cs2dsrv
5bc735a2f11779c1178c9273c6ed1d4115bc74fc
Added: - Some Buy Failed messages Fixed: - '\n' problem
diff --git a/Readme b/Readme index 5a003d2..f208ca4 100644 --- a/Readme +++ b/Readme @@ -1,27 +1,26 @@ Custom Counter Strike 2D Server a0.1 Copyright (C) 2010 by the authors of their respective files This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/ >. If you want to help me or you have questions contact me via Unrealsoftware-PM (Jermuk) or E-Mail < JExRMxUK (at)JExRMxUK (dot) DE > (Without x) Notice to windows: If you get linker errors, try to include the library libwsock32 or ws2_32.lib. Credits: - Main coder: Jermuk aka DÖNARMASTER from <www.Kebab-Clan.de> Thanks to: - Rynti and PopUp for helping me to write the OnFire routine -- Rynti for helping me to encrypt cs2d's packet structure -- DC, without him, I never understood cs2d's packet structure \ No newline at end of file +- Rynti for helping me to encrypt cs2d's packet structure \ No newline at end of file diff --git a/include/cross_layer.h b/include/cross_layer.h index d8eef64..dc18472 100644 --- a/include/cross_layer.h +++ b/include/cross_layer.h @@ -1,23 +1,23 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef CROSS_LAYER_H_INCLUDED -#define CROSS_LAYER_H_INCLUDED - -#include "main.h" - -int create_socket(void); -void error_exit(char *message); -void bind_socket(int *sock, unsigned long adress, unsigned short port); -void cleanup(void); -int udp_recieve(int socket, unsigned char *data, int length, - struct sockaddr_in *client); -void udp_send(int socket, unsigned char *data, int length, - struct sockaddr_in *client); -int mtime(void); -#endif // CROSS_LAYER_H_INCLUDED +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef CROSS_LAYER_H_INCLUDED +#define CROSS_LAYER_H_INCLUDED + +#include "main.h" + +int create_socket(void); +void error_exit(char *message); +void bind_socket(int *sock, unsigned long adress, unsigned short port); +void cleanup(void); +int udp_recieve(int socket, unsigned char *data, int length, + struct sockaddr_in *client); +void udp_send(int socket, unsigned char *data, int length, + struct sockaddr_in *client); +int mtime(void); +#endif // CROSS_LAYER_H_INCLUDED diff --git a/include/functions.h b/include/functions.h index 1fdc6be..86cde12 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,31 +1,31 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef FUNCTIONS_H_INCLUDED -#define FUNCTIONS_H_INCLUDED - -#include "main.h" -int IsPlayerKnown(struct in_addr ip, u_short port); -void ClearPlayer(int id); -void ClearAllPlayer(void); -void CheckForTimeout(int writesocket); -int GivePlayerWeapon(int id, int wpnid); -void RemovePlayerWeapon(int id, int wpnid); -void RemoveAllPlayerWeapon(int id); -int PlayerTimeout(int id); -unsigned short GetServerStatus(void); -unsigned short endian_swap_short(unsigned short *x); -unsigned int endian_swap_int(unsigned int *x); -int ValidatePaket(unsigned char *message, int id); -void PaketConfirmation(unsigned char *message, int id, int writesocket); -int CheckPlayerData(unsigned char *password); -unsigned char *GetEncodedString(unsigned char *string, int length); -void CheckAllPlayerForReload(int writesocket); -size_t u_strlen(unsigned char* buffer); - -#endif // FUNCTIONS_H_INCLUDED +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef FUNCTIONS_H_INCLUDED +#define FUNCTIONS_H_INCLUDED + +#include "main.h" +int IsPlayerKnown(struct in_addr ip, u_short port); +void ClearPlayer(int id); +void ClearAllPlayer(void); +void CheckForTimeout(int writesocket); +int GivePlayerWeapon(int id, int wpnid); +void RemovePlayerWeapon(int id, int wpnid); +void RemoveAllPlayerWeapon(int id); +int PlayerTimeout(int id); +unsigned short GetServerStatus(void); +unsigned short endian_swap_short(unsigned short *x); +unsigned int endian_swap_int(unsigned int *x); +int ValidatePaket(unsigned char *message, int id); +void PaketConfirmation(unsigned char *message, int id, int writesocket); +int CheckPlayerData(unsigned char *password); +unsigned char *GetEncodedString(unsigned char *string, int length); +void CheckAllPlayerForReload(int writesocket); +size_t u_strlen(unsigned char* buffer); + +#endif // FUNCTIONS_H_INCLUDED diff --git a/include/log.h b/include/log.h index ea4b8f0..c0df5a4 100644 --- a/include/log.h +++ b/include/log.h @@ -1,86 +1,86 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef LOG_H_INCLUDED -#define LOG_H_INCLUDED - -#include "main.h" - -void myprintf(char *string, ...); -void myprintf2(char *string, ...); - -/* - #define printf(...) file = fopen("log.txt","a+");\ - time(&rawtime );\ - timeinfo = localtime(&rawtime);\ - fprintf(file, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ - fprintf(file, __VA_ARGS__);\ - printf("[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ - printf(__VA_ARGS__);\ - fclose(file) - - #define eprintf(...) file = fopen("log.txt","a+");\ - fprintf(file, __VA_ARGS__);\ - fprintf(stdout, __VA_ARGS__);\ - fclose(file) - - extern FILE *file; - - extern time_t rawtime; - extern struct tm * timeinfo; - */ -#define printf(...) myprintf(__VA_ARGS__) -#define eprintf(...) myprintf2(__VA_ARGS__) - -#endif // LOG_H_INCLUDED - -/* - if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) - { - if((player[i].x - player[id].x) != 0 && (player[i].y - player[id].y) != 0) - { - float temprot = player[id].rotation; - double angle = atan2(player[i].x - player[id].x, player[i].y - player[id].y) * 180 / PI; - double angle2, angle3; - if(player[id].rotation < 0) - { - temprot += 180; - } - else if(player[id].rotation > 0) - { - temprot -= 180; - } - temprot = temprot *-1; - double victimangle = atan2(player[id].x - player[i].x, player[id].y - player[i].y) * 180 / PI; - double victimangle2 = victimangle + 90; - double victimangle3 = victimangle - 90; - int xPoint1, yPoint1; - int xPoint2, yPoint2; - xPoint1 = player[i].x + 16*cos(victimangle2*PI/180); - yPoint1 = player[i].y + 16*sin(victimangle2*PI/180); - xPoint2 = player[i].x + 16*cos(victimangle3*PI/180); - yPoint2 = player[i].y + 16*sin(victimangle3*PI/180); - - angle2 = atan2(xPoint1 - player[id].x, yPoint1 - player[id].y) * 180 / PI; - angle3 = atan2(xPoint2 - player[id].x, yPoint2 - player[id].y) * 180 / PI; - printf("(Debug2) %lf: %lf, %lf\n", temprot, angle2, angle3); - - xP = xM + r*cos(ß) - yP = yM + r*sin(ß) - - if((temprot <= angle2 && temprot >= angle3) || (temprot >= angle2 && temprot <= angle3)) - { - SendMessageToPlayer(id, "You hit someone!", 1, writesocket); - SendMessageToPlayer(i, "You were hitted by someone!", 1, writesocket); - OnHit(id, i, writesocket); - } - //SendMessageToPlayer(id, "Shooting not implemented yet!", 1, writesocket); - } - - } - */ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef LOG_H_INCLUDED +#define LOG_H_INCLUDED + +#include "main.h" + +void myprintf(char *string, ...); +void myprintf2(char *string, ...); + +/* + #define printf(...) file = fopen("log.txt","a+");\ + time(&rawtime );\ + timeinfo = localtime(&rawtime);\ + fprintf(file, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ + fprintf(file, __VA_ARGS__);\ + printf("[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ + printf(__VA_ARGS__);\ + fclose(file) + + #define eprintf(...) file = fopen("log.txt","a+");\ + fprintf(file, __VA_ARGS__);\ + fprintf(stdout, __VA_ARGS__);\ + fclose(file) + + extern FILE *file; + + extern time_t rawtime; + extern struct tm * timeinfo; + */ +#define printf(...) myprintf(__VA_ARGS__) +#define eprintf(...) myprintf2(__VA_ARGS__) + +#endif // LOG_H_INCLUDED + +/* + if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) + { + if((player[i].x - player[id].x) != 0 && (player[i].y - player[id].y) != 0) + { + float temprot = player[id].rotation; + double angle = atan2(player[i].x - player[id].x, player[i].y - player[id].y) * 180 / PI; + double angle2, angle3; + if(player[id].rotation < 0) + { + temprot += 180; + } + else if(player[id].rotation > 0) + { + temprot -= 180; + } + temprot = temprot *-1; + double victimangle = atan2(player[id].x - player[i].x, player[id].y - player[i].y) * 180 / PI; + double victimangle2 = victimangle + 90; + double victimangle3 = victimangle - 90; + int xPoint1, yPoint1; + int xPoint2, yPoint2; + xPoint1 = player[i].x + 16*cos(victimangle2*PI/180); + yPoint1 = player[i].y + 16*sin(victimangle2*PI/180); + xPoint2 = player[i].x + 16*cos(victimangle3*PI/180); + yPoint2 = player[i].y + 16*sin(victimangle3*PI/180); + + angle2 = atan2(xPoint1 - player[id].x, yPoint1 - player[id].y) * 180 / PI; + angle3 = atan2(xPoint2 - player[id].x, yPoint2 - player[id].y) * 180 / PI; + printf("(Debug2) %lf: %lf, %lf\n", temprot, angle2, angle3); + + xP = xM + r*cos(ß) + yP = yM + r*sin(ß) + + if((temprot <= angle2 && temprot >= angle3) || (temprot >= angle2 && temprot <= angle3)) + { + SendMessageToPlayer(id, "You hit someone!", 1, writesocket); + SendMessageToPlayer(i, "You were hitted by someone!", 1, writesocket); + OnHit(id, i, writesocket); + } + //SendMessageToPlayer(id, "Shooting not implemented yet!", 1, writesocket); + } + + } + */ diff --git a/include/main.h b/include/main.h index 24d671f..9a22ca0 100644 --- a/include/main.h +++ b/include/main.h @@ -1,51 +1,51 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef MAIN_H_INCLUDED -#define MAIN_H_INCLUDED - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <time.h> -#include <stdarg.h> //log.h -#include <math.h> //aim -#define PI 3.14159265 - -#ifdef _WIN32 -#include <winsock.h> -#include <io.h> -#else -#include <errno.h> -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <netdb.h> -#include <arpa/inet.h> -#include <unistd.h> - -#include <sys/select.h> //for select() -#endif - -/* Self-made includes */ -#include "log.h" -#include "settings.h" -#include "structs.h" -#include "weapons.h" - -#include "cross_layer.h" -#include "functions.h" -#include "sendto_functions.h" -#include "respond_messages.h" -#include "pakets.h" -#include "script-functions.h" -#include "map.h" - -int main(); - -#endif // MAIN_H_INCLUDED +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef MAIN_H_INCLUDED +#define MAIN_H_INCLUDED + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <stdarg.h> //log.h +#include <math.h> //aim +#define PI 3.14159265 + +#ifdef _WIN32 +#include <winsock.h> +#include <io.h> +#else +#include <errno.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netdb.h> +#include <arpa/inet.h> +#include <unistd.h> + +#include <sys/select.h> //for select() +#endif + +/* Self-made includes */ +#include "log.h" +#include "settings.h" +#include "structs.h" +#include "weapons.h" + +#include "cross_layer.h" +#include "functions.h" +#include "sendto_functions.h" +#include "respond_messages.h" +#include "pakets.h" +#include "script-functions.h" +#include "map.h" + +int main(); + +#endif // MAIN_H_INCLUDED diff --git a/include/map.h b/include/map.h index be19514..83be922 100644 --- a/include/map.h +++ b/include/map.h @@ -1,28 +1,28 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef MAP_H_INCLUDED -#define MAP_H_INCLUDED - -#include "main.h" - -void ReadMap(); -unsigned char *ReadLine(FILE *file); -unsigned char ReadByte(FILE *file); -int ReadInt(FILE *file); -#define MAX_SPAWNPOINTS 10 - -unsigned short tspawnx[MAX_SPAWNPOINTS]; -unsigned short tspawny[MAX_SPAWNPOINTS]; -unsigned short tspawncount; - -unsigned short ctspawnx[MAX_SPAWNPOINTS]; -unsigned short ctspawny[MAX_SPAWNPOINTS]; -unsigned short ctspawncount; - -#endif // MAP_H_INCLUDED +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef MAP_H_INCLUDED +#define MAP_H_INCLUDED + +#include "main.h" + +void ReadMap(); +unsigned char *ReadLine(FILE *file); +unsigned char ReadByte(FILE *file); +int ReadInt(FILE *file); +#define MAX_SPAWNPOINTS 10 + +unsigned short tspawnx[MAX_SPAWNPOINTS]; +unsigned short tspawny[MAX_SPAWNPOINTS]; +unsigned short tspawncount; + +unsigned short ctspawnx[MAX_SPAWNPOINTS]; +unsigned short ctspawny[MAX_SPAWNPOINTS]; +unsigned short ctspawncount; + +#endif // MAP_H_INCLUDED diff --git a/include/pakets.h b/include/pakets.h index 4ed289c..b4d980c 100644 --- a/include/pakets.h +++ b/include/pakets.h @@ -1,50 +1,52 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef PAKETS_H_INCLUDED -#define PAKETS_H_INCLUDED - -#include "main.h" -int unknown(unsigned char *message, int length, unsigned char *buffer, - int size, int position); -int connection_setup_unknown(unsigned char *message, int length, - struct in_addr ip, unsigned short port); -int connection_setup_known(unsigned char *message, int length, - struct in_addr ip, unsigned short port, int id); -int ping_ingame(unsigned char *message, int length, int id, int writesocket); -int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, - unsigned short port); -int confirmation_known(unsigned char *message, int length, int id, - int writesocket); -int fire(unsigned char *message, int length, int id, int writesocket); -int advanced_fire(unsigned char *message, int length, int id, int writesocket); -int buy(unsigned char *message, int length, int id, int writesocket); -int rotupdate(unsigned char *message, int length, int id, int writesocket); -int posupdatewalk(unsigned char *message, int length, int id, int writesocket); -int posupdaterun(unsigned char *message, int length, int id, int writesocket); -int posrotupdatewalk(unsigned char *message, int length, int id, - int writesocket); -int - posrotupdaterun(unsigned char *message, int length, int id, - int writesocket); -int respawnrequest(unsigned char *message, int length, int id, int writesocket); -int weaponchange(unsigned char *message, int length, int id, int writesocket); -int teamchange(unsigned char *message, int length, int id, int writesocket); -int ping_serverlist(unsigned char *message, int length, - struct sockaddr_in *client, int writesocket); -int serverinfo_request(unsigned char *message, int length, - struct sockaddr_in *client, int writesocket); -int joinroutine_unknown(unsigned char *message, int length, - struct sockaddr_in *client, int writesocket); -int specpos(unsigned char *message, int length, int id, int writesocket); -int chatmessage(unsigned char *message, int length, int id, int writesocket); -int joinroutine_known(unsigned char *message, int length, int id, - int writesocket); -int leave(int id, int writesocket); -int reload(unsigned char *message, int length, int id, int writesocket); -#endif // PAKETS_H_INCLUDED +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef PAKETS_H_INCLUDED +#define PAKETS_H_INCLUDED + +#include "main.h" +//#include "" + +int unknown(unsigned char *message, int length, unsigned char *buffer, + int size, int position); +int connection_setup_unknown(unsigned char *message, int length, + struct in_addr ip, unsigned short port); +int connection_setup_known(unsigned char *message, int length, + struct in_addr ip, unsigned short port, int id); +int ping_ingame(unsigned char *message, int length, int id, int writesocket); +int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, + unsigned short port); +int confirmation_known(unsigned char *message, int length, int id, + int writesocket); +int fire(unsigned char *message, int length, int id, int writesocket); +int advanced_fire(unsigned char *message, int length, int id, int writesocket); +int buy(unsigned char *message, int length, int id, int writesocket); +int rotupdate(unsigned char *message, int length, int id, int writesocket); +int posupdatewalk(unsigned char *message, int length, int id, int writesocket); +int posupdaterun(unsigned char *message, int length, int id, int writesocket); +int posrotupdatewalk(unsigned char *message, int length, int id, + int writesocket); +int posrotupdaterun(unsigned char *message, int length, int id, + int writesocket); +int respawnrequest(unsigned char *message, int length, int id, int writesocket); +int weaponchange(unsigned char *message, int length, int id, int writesocket); +int teamchange(unsigned char *message, int length, int id, int writesocket); +int ping_serverlist(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket); +int serverinfo_request(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket); +int joinroutine_unknown(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket); +int specpos(unsigned char *message, int length, int id, int writesocket); +int chatmessage(unsigned char *message, int length, int id, int writesocket); +int joinroutine_known(unsigned char *message, int length, int id, + int writesocket); +int leave(int id, int writesocket); +int reload(unsigned char *message, int length, int id, int writesocket); +int spray(unsigned char *message, int length, int id, int writesocket); +#endif // PAKETS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index c352e75..797ab48 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,36 +1,39 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef RESPOND_MESSAGES_H_INCLUDED -#define RESPOND_MESSAGES_H_INCLUDED -#include "main.h" - -void SendSpawnMessage(int id, unsigned short x, unsigned short y, - int writesocket); -void SendAdvancedFireMessage(int id, int status, int writesocket); -void SendFireMessage(int id, int writesocket); -void SendBuyMessage(int id, int wpnid, int writesocket); -void SendHitMessage(int id, int victim, int health, int writesocket); -void SendWeaponChangeMessage(int id, int wpnid, int writesocket); -void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, - int writesocket); -void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, - float rotation, int writesocket); -void SendRotUpdate(int id, float rotation, int writesocket); -void SendMessageToPlayer(int id, char *message, int status, int writesocket); -void SendMessageToAll(char *message, int status, int writesocket); -void SendJoinMessage(int id, int writesocket); -void SendLeaveMessage(int id, int writesocket); -void SendChatMessage(int id, unsigned char *message, int team, int writesocket); -void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, - int writesocket); -void PingAllPlayer(int writesocket, time_t *firsttime); -void SendReloadMessage(int id, int status, int writesocket); -void SendPingList(int writesocket); - -#endif // RESPOND_MESSAGES_H_INCLUDED +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef RESPOND_MESSAGES_H_INCLUDED +#define RESPOND_MESSAGES_H_INCLUDED +#include "main.h" + +void SendSpawnMessage(int id, unsigned short x, unsigned short y, + int writesocket); +void SendAdvancedFireMessage(int id, int status, int writesocket); +void SendFireMessage(int id, int writesocket); +void SendBuyMessage(int id, int wpnid, int writesocket); +void SendHitMessage(int id, int victim, int health, int writesocket); +void SendWeaponChangeMessage(int id, int wpnid, int writesocket); +void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, + int writesocket); +void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, + float rotation, int writesocket); +void SendRotUpdate(int id, float rotation, int writesocket); +void SendMessageToPlayer(int id, char *message, int status, int writesocket); +void SendMessageToAll(char *message, int status, int writesocket); +void SendJoinMessage(int id, int writesocket); +void SendLeaveMessage(int id, int writesocket); +void SendChatMessage(int id, unsigned char *message, int team, int writesocket); +void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, + int writesocket); +void PingAllPlayer(int writesocket, time_t *firsttime); +void SendReloadMessage(int id, int status, int writesocket); +void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, int writesocket); +void SendKillMessage(int id, int writesocket); +void SendPingList(int writesocket); +void SendBuyFailedMessage(int id, int status, int writesocket); + +#endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/script-functions.h b/include/script-functions.h index a68a047..bb05b5e 100644 --- a/include/script-functions.h +++ b/include/script-functions.h @@ -1,35 +1,35 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef SCRIPT_H_INCLUDED -#define SCRIPT_H_INCLUDED - -#include "main.h" - -int OnJoin(int id, int writesocket); -int OnLeave(int id, int writesocket); -int OnSpecmove(int id, int newx, int newy, int writesocket); -int OnServerStart(); -int OnExit(); -int OnRespawnRequest(int id, int writesocket); -int OnRespawn(int id, int writesocket); -int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); -int OnAdvancedFire(int id, int status, int writesocket); -int OnFire(int id, int writesocket); -int OnHit(int hitter, int victim, int writesocket); -int OnBuyAttempt(int id, int wpnid, int writesocket); -int OnBuy(int id, int wpnid, int writesocket); -int OnKill(int hitter, int victim, int wpnid, int writesocket); -int OnChatMessage(int id, unsigned char *message, int team, int writesocket); -int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, - int writesocket); -int OnTeamChange(int id, unsigned char team, unsigned char skin, - int writesocket); -int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, - int writesocket); -#endif +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef SCRIPT_H_INCLUDED +#define SCRIPT_H_INCLUDED + +#include "main.h" + +int OnJoin(int id, int writesocket); +int OnLeave(int id, int writesocket); +int OnSpecmove(int id, int newx, int newy, int writesocket); +int OnServerStart(); +int OnExit(); +int OnRespawnRequest(int id, int writesocket); +int OnRespawn(int id, int writesocket); +int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); +int OnAdvancedFire(int id, int status, int writesocket); +int OnFire(int id, int writesocket); +int OnHit(int hitter, int victim, int writesocket); +int OnBuyAttempt(int id, int wpnid, int writesocket); +int OnBuy(int id, int wpnid, int writesocket); +int OnKill(int hitter, int victim, int wpnid, int writesocket); +int OnChatMessage(int id, unsigned char *message, int team, int writesocket); +int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, + int writesocket); +int OnTeamChange(int id, unsigned char team, unsigned char skin, + int writesocket); +int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, + int writesocket); +#endif diff --git a/include/sendto_functions.h b/include/sendto_functions.h index 71242d3..118ec89 100644 --- a/include/sendto_functions.h +++ b/include/sendto_functions.h @@ -1,22 +1,22 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef SENDTO_FUNCTIONS_H_ -#define SENDTO_FUNCTIONS_H_ - -#include "main.h" -void SendToPlayer(unsigned char *message, int length, int id, int reliable, - int writesocket); -void SendToAll(unsigned char *message, int length, int reliable, - int writesocket); -void SendToTeam(unsigned char *message, int length, int reliable, int team, - int writesocket); -void SendToAllOther(int id, unsigned char *message, int length, int reliable, - int writesocket); - -#endif /* SENDTO_FUNCTIONS_H_ */ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef SENDTO_FUNCTIONS_H_ +#define SENDTO_FUNCTIONS_H_ + +#include "main.h" +void SendToPlayer(unsigned char *message, int length, int id, int reliable, + int writesocket); +void SendToAll(unsigned char *message, int length, int reliable, + int writesocket); +void SendToTeam(unsigned char *message, int length, int reliable, int team, + int writesocket); +void SendToAllOther(int id, unsigned char *message, int length, int reliable, + int writesocket); + +#endif /* SENDTO_FUNCTIONS_H_ */ diff --git a/include/weapons.h b/include/weapons.h index 5804645..20e323f 100644 --- a/include/weapons.h +++ b/include/weapons.h @@ -1,21 +1,21 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#ifndef WEAPONS_H_INCLUDED -#define WEAPONS_H_INCLUDED - -#include "main.h" -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, - short wpndmg_z2, short freq, short speed, short slot, short price, - short range, short accuracy, short ammo1, short ammo2, int reloadtime, - short special, short team); -void WeaponInit(); - -struct WEAPON weapons[100]; - -#endif // WEAPONS_H_INCLUDED +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#ifndef WEAPONS_H_INCLUDED +#define WEAPONS_H_INCLUDED + +#include "main.h" +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, + short wpndmg_z2, short freq, short speed, short slot, short price, + short range, short accuracy, short ammo1, short ammo2, int reloadtime, + short special, short team); +void WeaponInit(); + +struct WEAPON weapons[100]; + +#endif // WEAPONS_H_INCLUDED diff --git a/src/cross_layer.c b/src/cross_layer.c index ccad392..4b36da7 100644 --- a/src/cross_layer.c +++ b/src/cross_layer.c @@ -1,203 +1,203 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/cross_layer.h" -/** - * \fn int create_socket(void) - * \brief creates a socket - * \return socketnumber or 0 if failed - */ -int create_socket(void) -{ -#ifdef _WIN32 - - WSADATA wsa; - if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) - { - error_exit("WSAStartup() failed"); - } - else - { - int sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - { - error_exit("socket() failed"); - } - return sock; - } -#else - - const int y = 1; - int sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - { - error_exit("socket() failed"); - } - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); - return sock; - -#endif - return 0; -} - -/** - * \fn int bind_socket(int *sock, unsigned long adress, unsigned short port) - * \brief bind a socket to a specific IP and port - * \param *sock socket to bind - * \param adress ip-address to bind - * \param port port to bind - */ -void bind_socket(int *sock, unsigned long adress, unsigned short port) -{ -#ifdef _WIN32 - struct sockaddr_in server; - - memset(&server, 0, sizeof(server)); - server.sin_family = AF_INET; - server.sin_addr.s_addr = htonl(adress); - server.sin_port = htons(port); - if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) - { - error_exit("bind() failed"); - } -#else - struct sockaddr_in server; - memset(&server, 0, sizeof (server)); - server.sin_family = AF_INET; - server.sin_addr.s_addr = htonl(adress); - server.sin_port = htons(port); - if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) - { - error_exit("bind() failed"); - } -#endif -} - -/** - * \fn int error_exit(char *message) - * \brief Show a error message and exit the programm - * \param *message message to display - */ -void error_exit(char *message) -{ - printf("%s", message); - /* - printf("%s: %d\n", message, WSAGetLastError()); - //debug(stderr); - #else - printf("%s: %s\n", message, strerror(errno)); - //debug(stderr); - */ - - exit(EXIT_FAILURE); -} - -/** - * \fn cleanup(void) - * \brief clean the socket - */ -void cleanup(void) -{ - OnExit(); -#ifdef _WIN32 - WSACleanup(); -#else - /* Nichts zu tun */ -#endif -} - -/** - * \fn mtime(void) - * \brief return the actually time in miliseconds for win and linux - * \return time in ms - */ - -int mtime(void) -{ -#ifdef _WIN32 - return GetTickCount(); -#else - struct timeval tv; - gettimeofday(&tv,NULL); - return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); -#endif -} - -/** - * \fn void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) - * \brief send a message over a specific socket to a client - * \param *socket socket to send over - * \param *data data to send - * \param length size of *data - * \param *client sockaddr_in struct to send data to - */ -void udp_send(int socket, unsigned char *data, int length, - struct sockaddr_in *client) -{ - int rc; - - //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); - rc = sendto(socket, (char*) data, length, 0, (struct sockaddr *) client, - sizeof(*client)); - /* - int i; - for(i = 0; i <= length; i++) - { - printf("%d-", data[i]); - } - printf("\n"); - */ - -#ifdef _WIN32 - if (rc == SOCKET_ERROR) - error_exit("sendto() failed"); -#else - if (rc < 0) - error_exit("sendto() failed"); -#endif - //else - //printf("Message sent!\n"); -} - -/** - * \fn int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) - * \brief Recieves a message on a specicific socket and save (if something recieved) the data - * \param socket socket to recieve - * \param *data pointer where the data should be saved - * \param length max length of *data - * \param *client pointer where the clientdata (ip, ...) should be saved - * \return length of read data - */ -int udp_recieve(int socket, unsigned char *data, int length, - struct sockaddr_in *client) -{ - struct sockaddr_in newclient; - int len; - int size; - len = sizeof(struct sockaddr_in); - size = recvfrom(socket, (char*) data, length, 0, - (struct sockaddr *) &newclient, &len); - *client = newclient; -#ifdef _WIN32 - if (size == SOCKET_ERROR) - { - error_exit("recvfrom() failed"); - } -#else - if (size < 0) - { - error_exit("recvfrom() failed"); - } -#endif - else - { - return size; - } - return 0; -} - +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/cross_layer.h" +/** + * \fn int create_socket(void) + * \brief creates a socket + * \return socketnumber or 0 if failed + */ +int create_socket(void) +{ +#ifdef _WIN32 + + WSADATA wsa; + if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) + { + error_exit("WSAStartup() failed"); + } + else + { + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + { + error_exit("socket() failed"); + } + return sock; + } +#else + + const int y = 1; + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + { + error_exit("socket() failed"); + } + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); + return sock; + +#endif + return 0; +} + +/** + * \fn int bind_socket(int *sock, unsigned long adress, unsigned short port) + * \brief bind a socket to a specific IP and port + * \param *sock socket to bind + * \param adress ip-address to bind + * \param port port to bind + */ +void bind_socket(int *sock, unsigned long adress, unsigned short port) +{ +#ifdef _WIN32 + struct sockaddr_in server; + + memset(&server, 0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = htonl(adress); + server.sin_port = htons(port); + if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) + { + error_exit("bind() failed"); + } +#else + struct sockaddr_in server; + memset(&server, 0, sizeof (server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = htonl(adress); + server.sin_port = htons(port); + if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) + { + error_exit("bind() failed"); + } +#endif +} + +/** + * \fn int error_exit(char *message) + * \brief Show a error message and exit the programm + * \param *message message to display + */ +void error_exit(char *message) +{ + printf("%s", message); + /* + printf("%s: %d\n", message, WSAGetLastError()); + //debug(stderr); + #else + printf("%s: %s\n", message, strerror(errno)); + //debug(stderr); + */ + + exit(EXIT_FAILURE); +} + +/** + * \fn cleanup(void) + * \brief clean the socket + */ +void cleanup(void) +{ + OnExit(); +#ifdef _WIN32 + WSACleanup(); +#else + /* Nichts zu tun */ +#endif +} + +/** + * \fn mtime(void) + * \brief return the actually time in miliseconds for win and linux + * \return time in ms + */ + +int mtime(void) +{ +#ifdef _WIN32 + return GetTickCount(); +#else + struct timeval tv; + gettimeofday(&tv,NULL); + return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); +#endif +} + +/** + * \fn void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) + * \brief send a message over a specific socket to a client + * \param *socket socket to send over + * \param *data data to send + * \param length size of *data + * \param *client sockaddr_in struct to send data to + */ +void udp_send(int socket, unsigned char *data, int length, + struct sockaddr_in *client) +{ + int rc; + + //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); + rc = sendto(socket, (char*) data, length, 0, (struct sockaddr *) client, + sizeof(*client)); + /* + int i; + for(i = 0; i <= length; i++) + { + printf("%d-", data[i]); + } + printf("\n"); + */ + +#ifdef _WIN32 + if (rc == SOCKET_ERROR) + error_exit("sendto() failed"); +#else + if (rc < 0) + error_exit("sendto() failed"); +#endif + //else + //printf("Message sent!\n"); +} + +/** + * \fn int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) + * \brief Recieves a message on a specicific socket and save (if something recieved) the data + * \param socket socket to recieve + * \param *data pointer where the data should be saved + * \param length max length of *data + * \param *client pointer where the clientdata (ip, ...) should be saved + * \return length of read data + */ +int udp_recieve(int socket, unsigned char *data, int length, + struct sockaddr_in *client) +{ + struct sockaddr_in newclient; + int len; + int size; + len = sizeof(struct sockaddr_in); + size = recvfrom(socket, (char*) data, length, 0, + (struct sockaddr *) &newclient, &len); + *client = newclient; +#ifdef _WIN32 + if (size == SOCKET_ERROR) + { + error_exit("recvfrom() failed"); + } +#else + if (size < 0) + { + error_exit("recvfrom() failed"); + } +#endif + else + { + return size; + } + return 0; +} + diff --git a/src/functions.c b/src/functions.c index 551581d..0d8607f 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,438 +1,438 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/functions.h" - -/** - * \fn int IsPlayerKnown(struct in_addr ip, u_short port) - * \brief checks if a player is already known - * \param ip client's ip - * \param port client's port - * \return the playerid or 0 if not found - */ -int IsPlayerKnown(struct in_addr ip, u_short port) -{ - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port - == player[i].port) - { - return i; - } - } - return -1; -} - -/** - * \fn void ClearPlayer(int id) - * \brief clear all player variables - */ -void ClearPlayer(int id) -{ - player[id].used = 0; - player[id].client_nummer = 0; - player[id].server_nummer = 0; - player[id].lastpaket = 0; - player[id].joinstatus = 0; - - free(player[id].name); - player[id].name = NULL; - free(player[id].spraylogo); - player[id].spraylogo = NULL; - free(player[id].win); - player[id].win = NULL; - free(player[id].usgn); - player[id].usgn = NULL; - player[id].version = 0; - - player[id].team = 0; - player[id].deaths = 0; - player[id].score = 0; - - player[id].x = 0; - player[id].y = 0; - - player[id].health = 0; - player[id].armor = 0; - - player[id].actualweapon = 0; - player[id].reloading = 0; - player[id].reloadtimer = 0; - player[id].zoomtimer = 0; - player[id].firetimer = 0; - - int i; - for (i = 0; i <= 9; i++) - { - player[id].slot[i].id = 0; - } - player[id].rotation = 0; - - player[id].dead = 1; - - player[id].start = 0; - player[id].money = mp_startmoney; - player[id].zoommode = 0; - - /* Address*/ - player[id].port = 0; - //player[id].ip = ""; -} - -/** - * \fn void ClearAllPlayer(void) - * \brief clear all player variables - */ -void ClearAllPlayer(void) -{ - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - ClearPlayer(i); - } -} - -/** - * \fn void CheckForTimeout(int writesocket) - * \brief check all player for timeout - */ -void CheckForTimeout(int writesocket) -{ - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && PlayerTimeout(i)) - { - printf("Client %d timed out!\n", i); - SendLeaveMessage(i, writesocket); - ClearPlayer(i); - } - } -} -/** - * \fn int GivePlayerWeapon(int id, int wpnid) - * \brief adds an specific weapon to a player - * \param id player-id - * \param wpnid weapon-id - * \return the slot-id or 0 if not found - */ -int GivePlayerWeapon(int id, int wpnid) -{ - int i; - for (i = 0; i <= 9; i++) - { - if (player[id].slot[i].id == 0) - { - player[id].slot[i].id = wpnid; - player[id].slot[i].slot = weapons[wpnid].slot; - player[id].slot[i].ammo1 = weapons[wpnid].ammo1; - player[id].slot[i].ammo2 = weapons[wpnid].ammo2; - return i; - } - } - return 0; -} -/** - * \fn void RemovePlayerWeapon(int id, int wpnid) - * \brief removes an specific weapon to a player - * \param id player-id - * \param wpnid weapon-id - */ -void RemovePlayerWeapon(int id, int wpnid) -{ - int i; - for (i = 0; i <= 9; i++) - { - if (player[id].slot[i].id == wpnid) - { - player[id].slot[i].id = 0; - player[id].slot[i].slot = 0; - player[id].slot[i].ammo1 = 0; - player[id].slot[i].ammo2 = 0; - break; - } - } -} -/** - * \fn void RemoveAllPlayerWeapon(int id) - * \brief remove all weapons from a player - * \param id player-id - */ -void RemoveAllPlayerWeapon(int id) -{ - int i; - for (i = 0; i <= 9; i++) - { - player[id].slot[i].id = 0; - player[id].slot[i].slot = 0; - player[id].slot[i].ammo1 = 0; - player[id].slot[i].ammo2 = 0; - player[id].slot[i].special = 0; - player[id].zoommode = 0; - - } -} - -/** - * \fn int PlayerTimeout(int id) - * \brief checks if a specific player is timeout - * \param id player-id - * \return 1 - timeout; 0 - success - * - */ -int PlayerTimeout(int id) -{ - //id = 0; - - time_t actualtime; - time(&actualtime); - - if (((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket - != 0) - { - return 1; - } - return 0; -} - -/** - * \fn unsigned short GetServerStatus(void) - * \brief needs for serverlist - * \return serverstatus - */ -unsigned short GetServerStatus(void) -{ - unsigned short serverstatus = 0; - if (strcmp((char*) sv_password, "")) - { - serverstatus += 1; - } - if (sv_usgnonly == 1) - { - serverstatus += 2; - } - if (sv_fow == 1) - { - serverstatus += 4; - } - if (sv_friendlyfire == 1) - { - serverstatus += 8; - } - if (1) //Same Version? - { - serverstatus += 16; - } - if (sv_gamemode != 0) - { - serverstatus += 32; - } - if (0) //LuaScripts - { - serverstatus += 64; - } - if (1) //Dedicated - { - serverstatus += 128; - } - return serverstatus; -} - -/** - * \fn unsigned short endian_swap_short(unsigned short *x) - * \brief swap the endian for a short - * \param *x pointer to an unsigned short - * \return the endian-changed unsigned short - */ -unsigned short endian_swap_short(unsigned short *x) -{ - *x = (*x >> 8) | (*x << 8); - return *x; -} -/** - * \fn unsigned int endian_swap_int(unsigned int *x) - * \brief swap the endian for an int - * \param *x pointer to an int - * \return the endian-changed int - */ -unsigned int endian_swap_int(unsigned int *x) -{ - *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x - << 24); - return *x; -} - -/** - * \fn int ValidatePaket(char *message, int id) - * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary - * \param *message pointer to the message - * \param id player-id - * \return 0 if invalid; 1 if valid - */ -int ValidatePaket(unsigned char *message, int id) -{ - unsigned short *pTempNummer = malloc(sizeof(unsigned short)); - pTempNummer[0] = message[0]; - pTempNummer[1] = message[1]; - if (*pTempNummer % 2 != 0) - { - if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) - > (player[id].client_nummer + 2)) - { - printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); - free(pTempNummer); - return 0; - } - } - if (*pTempNummer - 1 > player[id].client_nummer) - { - player[id].client_nummer = *pTempNummer; - } - /* - unsigned short *pNummer = &player[id].client_nummer; - pNummer[0] = buffer[0]; - pNummer[1] = buffer[1]; - */ - free(pTempNummer); - return 1; -} -/** - * \fn void PaketConfirmation(char *message, int id, int writesocket) - * \brief sends an confirmation to a player if necessary - * \param *message pointer to the message - * \param id player-id - */ -void PaketConfirmation(unsigned char *message, int id, int writesocket) -{ - unsigned short *pTempNummer = malloc(sizeof(unsigned short)); - pTempNummer[0] = message[0]; - pTempNummer[1] = message[1]; - if (*pTempNummer % 2 == 0) - { - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - buffer[0] = 0x01; - memcpy(buffer + 1, pTempNummer, 2); - - SendToPlayer(buffer, stringsize, id, 0, writesocket); - - free(buffer); - } - free(pTempNummer); -} -/** - * \fn int CheckPlayerData(char *password) - * \brief check all player data and looks if he/she can join - * \param *password pointer to the password - * \return the error number or 0 - */ -int CheckPlayerData(unsigned char *password) -{ - if (strcmp((char*) sv_password, (char*) password) != 0) - { - printf("Password wrong!\n"); - return 1; - } - if (sv_maxplayers == onlineplayer) - { - printf("Server full!\n"); - return 3; - } - /* - 0 - Normal - 1 - Password wrong - 2 - USGN only - 3 - Server full - 4 - Banned - 5 - Another Game Version - 6 - ?? - 7 - Can't validate user (USGN offline) - 8 - ?? - 9 - Connection already exists - 10 - Wrong client (pre_authcode) - 11 - Different map (temp, etc.) - 12 - Map unknown (maptransfer disabled) - 13++ - Failed to join - */ - - return 0; -} - -/** - * \fn unsigned char *GetEncodedString(unsigned char *string, int length) - * \brief convert the playername into cs2d format - * \param *string playername - * \param length length from playername - * \return the converted name - */ -unsigned char *GetEncodedString(unsigned char *string, int length) -{ - unsigned char *buffer = malloc(length + 1); //+1 need for \0 - if (buffer == NULL) - error_exit("Memory error ( GetEncodedString() )\n"); - - int i; - for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) - { - if ((i % 3) == 0) - { - buffer[i] = string[i] + 110; - } - else if ((i % 3) == 1) - { - buffer[i] = string[i] + 97; - } - else if ((i % 3) == 2) - { - buffer[i] = string[i] + 109; - } - } - buffer[length] = '\0'; - - return buffer; -} - -/** - * \fn void CheckAllPlayerForReload(int writesocket) - * \brief check all player if their reload is ended, - * send message if necessary, and rise their magazine - */ -void CheckAllPlayerForReload(int writesocket) -{ - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].reloading != 0) - { - if (player[i].reloadtimer <= mtime()) - { - SendReloadMessage(i, 2, writesocket); - if (player[i].slot[player[i].reloading].ammo2 - -= player[i].slot[player[i].reloading].ammo1 > 0) - { - player[i].slot[player[i].reloading].ammo2 - -= player[i].slot[player[i].reloading].ammo1; - player[i].slot[player[i].reloading].ammo1 - = weapons[player[i].slot[player[i].reloading].id].ammo1; - } - else - { - player[i].slot[player[i].reloading].ammo1 - = player[i].slot[player[i].reloading].ammo2; - } - player[i].reloading = 0; - } - } - } -} - -size_t u_strlen(unsigned char* buffer) -{ - return strlen((char*) buffer); -} +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/functions.h" + +/** + * \fn int IsPlayerKnown(struct in_addr ip, u_short port) + * \brief checks if a player is already known + * \param ip client's ip + * \param port client's port + * \return the playerid or 0 if not found + */ +int IsPlayerKnown(struct in_addr ip, u_short port) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port + == player[i].port) + { + return i; + } + } + return -1; +} + +/** + * \fn void ClearPlayer(int id) + * \brief clear all player variables + */ +void ClearPlayer(int id) +{ + player[id].used = 0; + player[id].client_nummer = 0; + player[id].server_nummer = 0; + player[id].lastpaket = 0; + player[id].joinstatus = 0; + + free(player[id].name); + player[id].name = NULL; + free(player[id].spraylogo); + player[id].spraylogo = NULL; + free(player[id].win); + player[id].win = NULL; + free(player[id].usgn); + player[id].usgn = NULL; + player[id].version = 0; + + player[id].team = 0; + player[id].deaths = 0; + player[id].score = 0; + + player[id].x = 0; + player[id].y = 0; + + player[id].health = 0; + player[id].armor = 0; + + player[id].actualweapon = 0; + player[id].reloading = 0; + player[id].reloadtimer = 0; + player[id].zoomtimer = 0; + player[id].firetimer = 0; + + int i; + for (i = 0; i <= 9; i++) + { + player[id].slot[i].id = 0; + } + player[id].rotation = 0; + + player[id].dead = 1; + + player[id].start = 0; + player[id].money = mp_startmoney; + player[id].zoommode = 0; + + /* Address*/ + player[id].port = 0; + //player[id].ip = ""; +} + +/** + * \fn void ClearAllPlayer(void) + * \brief clear all player variables + */ +void ClearAllPlayer(void) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + ClearPlayer(i); + } +} + +/** + * \fn void CheckForTimeout(int writesocket) + * \brief check all player for timeout + */ +void CheckForTimeout(int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && PlayerTimeout(i)) + { + printf("Client %d timed out!\n", i); + SendLeaveMessage(i, writesocket); + ClearPlayer(i); + } + } +} +/** + * \fn int GivePlayerWeapon(int id, int wpnid) + * \brief adds an specific weapon to a player + * \param id player-id + * \param wpnid weapon-id + * \return the slot-id or 0 if not found + */ +int GivePlayerWeapon(int id, int wpnid) +{ + int i; + for (i = 0; i <= 9; i++) + { + if (player[id].slot[i].id == 0) + { + player[id].slot[i].id = wpnid; + player[id].slot[i].slot = weapons[wpnid].slot; + player[id].slot[i].ammo1 = weapons[wpnid].ammo1; + player[id].slot[i].ammo2 = weapons[wpnid].ammo2; + return i; + } + } + return 0; +} +/** + * \fn void RemovePlayerWeapon(int id, int wpnid) + * \brief removes an specific weapon to a player + * \param id player-id + * \param wpnid weapon-id + */ +void RemovePlayerWeapon(int id, int wpnid) +{ + int i; + for (i = 0; i <= 9; i++) + { + if (player[id].slot[i].id == wpnid) + { + player[id].slot[i].id = 0; + player[id].slot[i].slot = 0; + player[id].slot[i].ammo1 = 0; + player[id].slot[i].ammo2 = 0; + break; + } + } +} +/** + * \fn void RemoveAllPlayerWeapon(int id) + * \brief remove all weapons from a player + * \param id player-id + */ +void RemoveAllPlayerWeapon(int id) +{ + int i; + for (i = 0; i <= 9; i++) + { + player[id].slot[i].id = 0; + player[id].slot[i].slot = 0; + player[id].slot[i].ammo1 = 0; + player[id].slot[i].ammo2 = 0; + player[id].slot[i].special = 0; + player[id].zoommode = 0; + + } +} + +/** + * \fn int PlayerTimeout(int id) + * \brief checks if a specific player is timeout + * \param id player-id + * \return 1 - timeout; 0 - success + * + */ +int PlayerTimeout(int id) +{ + //id = 0; + + time_t actualtime; + time(&actualtime); + + if (((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket + != 0) + { + return 1; + } + return 0; +} + +/** + * \fn unsigned short GetServerStatus(void) + * \brief needs for serverlist + * \return serverstatus + */ +unsigned short GetServerStatus(void) +{ + unsigned short serverstatus = 0; + if (strcmp((char*) sv_password, "")) + { + serverstatus += 1; + } + if (sv_usgnonly == 1) + { + serverstatus += 2; + } + if (sv_fow == 1) + { + serverstatus += 4; + } + if (sv_friendlyfire == 1) + { + serverstatus += 8; + } + if (1) //Same Version? + { + serverstatus += 16; + } + if (sv_gamemode != 0) + { + serverstatus += 32; + } + if (0) //LuaScripts + { + serverstatus += 64; + } + if (1) //Dedicated + { + serverstatus += 128; + } + return serverstatus; +} + +/** + * \fn unsigned short endian_swap_short(unsigned short *x) + * \brief swap the endian for a short + * \param *x pointer to an unsigned short + * \return the endian-changed unsigned short + */ +unsigned short endian_swap_short(unsigned short *x) +{ + *x = (*x >> 8) | (*x << 8); + return *x; +} +/** + * \fn unsigned int endian_swap_int(unsigned int *x) + * \brief swap the endian for an int + * \param *x pointer to an int + * \return the endian-changed int + */ +unsigned int endian_swap_int(unsigned int *x) +{ + *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x + << 24); + return *x; +} + +/** + * \fn int ValidatePaket(char *message, int id) + * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary + * \param *message pointer to the message + * \param id player-id + * \return 0 if invalid; 1 if valid + */ +int ValidatePaket(unsigned char *message, int id) +{ + unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + if (*pTempNummer % 2 != 0) + { + if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) + > (player[id].client_nummer + 2)) + { + printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); + free(pTempNummer); + return 0; + } + } + if (*pTempNummer - 1 > player[id].client_nummer) + { + player[id].client_nummer = *pTempNummer; + } + /* + unsigned short *pNummer = &player[id].client_nummer; + pNummer[0] = buffer[0]; + pNummer[1] = buffer[1]; + */ + free(pTempNummer); + return 1; +} +/** + * \fn void PaketConfirmation(char *message, int id, int writesocket) + * \brief sends an confirmation to a player if necessary + * \param *message pointer to the message + * \param id player-id + */ +void PaketConfirmation(unsigned char *message, int id, int writesocket) +{ + unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + if (*pTempNummer % 2 == 0) + { + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + buffer[0] = 0x01; + memcpy(buffer + 1, pTempNummer, 2); + + SendToPlayer(buffer, stringsize, id, 0, writesocket); + + free(buffer); + } + free(pTempNummer); +} +/** + * \fn int CheckPlayerData(char *password) + * \brief check all player data and looks if he/she can join + * \param *password pointer to the password + * \return the error number or 0 + */ +int CheckPlayerData(unsigned char *password) +{ + if (strcmp((char*) sv_password, (char*) password) != 0) + { + printf("Password wrong!\n"); + return 1; + } + if (sv_maxplayers == onlineplayer) + { + printf("Server full!\n"); + return 3; + } + /* + 0 - Normal + 1 - Password wrong + 2 - USGN only + 3 - Server full + 4 - Banned + 5 - Another Game Version + 6 - ?? + 7 - Can't validate user (USGN offline) + 8 - ?? + 9 - Connection already exists + 10 - Wrong client (pre_authcode) + 11 - Different map (temp, etc.) + 12 - Map unknown (maptransfer disabled) + 13++ - Failed to join + */ + + return 0; +} + +/** + * \fn unsigned char *GetEncodedString(unsigned char *string, int length) + * \brief convert the playername into cs2d format + * \param *string playername + * \param length length from playername + * \return the converted name + */ +unsigned char *GetEncodedString(unsigned char *string, int length) +{ + unsigned char *buffer = malloc(length + 1); //+1 need for \0 + if (buffer == NULL) + error_exit("Memory error ( GetEncodedString() )\n"); + + int i; + for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) + { + if ((i % 3) == 0) + { + buffer[i] = string[i] + 110; + } + else if ((i % 3) == 1) + { + buffer[i] = string[i] + 97; + } + else if ((i % 3) == 2) + { + buffer[i] = string[i] + 109; + } + } + buffer[length] = '\0'; + + return buffer; +} + +/** + * \fn void CheckAllPlayerForReload(int writesocket) + * \brief check all player if their reload is ended, + * send message if necessary, and rise their magazine + */ +void CheckAllPlayerForReload(int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].reloading != 0) + { + if (player[i].reloadtimer <= mtime()) + { + SendReloadMessage(i, 2, writesocket); + if (player[i].slot[player[i].reloading].ammo2 + -= player[i].slot[player[i].reloading].ammo1 > 0) + { + player[i].slot[player[i].reloading].ammo2 + -= player[i].slot[player[i].reloading].ammo1; + player[i].slot[player[i].reloading].ammo1 + = weapons[player[i].slot[player[i].reloading].id].ammo1; + } + else + { + player[i].slot[player[i].reloading].ammo1 + = player[i].slot[player[i].reloading].ammo2; + } + player[i].reloading = 0; + } + } + } +} + +size_t u_strlen(unsigned char* buffer) +{ + return strlen((char*) buffer); +} diff --git a/src/main.c b/src/main.c index df01197..7b193fe 100644 --- a/src/main.c +++ b/src/main.c @@ -1,254 +1,258 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); while (1) { CheckForTimeout(readsocket); PingAllPlayer(readsocket, &firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); select(readsocket + 1, &descriptor, NULL, NULL, NULL); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; + case 28: + // Spray 28 - 0 - x x - y y - color + rtn = spray(message, tempsize, id, readsocket); + break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return EXIT_SUCCESS; } diff --git a/src/map.c b/src/map.c index a152c7a..49c470d 100644 --- a/src/map.c +++ b/src/map.c @@ -1,219 +1,219 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/map.h" - -/** - * \fn void ReadMap() - * \brief reads the map and put all needed information into a variable - * needed: tspawn and ctspawn - */ -void ReadMap() -{ - FILE *file; - int i; - tspawncount = 0; - ctspawncount = 0; - - char *mappath = malloc(u_strlen(sv_map) + 5); - memcpy(mappath, sv_map, u_strlen(sv_map)); - memcpy(mappath + u_strlen(sv_map), ".map\0", 5); - - file = fopen(mappath, "rb"); - if (file == NULL) - error_exit("Map not found.. Abort\n"); - else printf("Loading '%s'..", mappath); - - free(mappath); - - //------------------------------ - unsigned char *mapheader = ReadLine(file); - for (i = 1; i <= 9; i++) - ReadByte(file); - for (i = 1; i <= 10; i++) - ReadInt(file); - for (i = 1; i <= 10; i++) - ReadLine(file); - unsigned char *code = ReadLine(file); - unsigned char *tileset = ReadLine(file); - unsigned char loaded = ReadByte(file); - int maxx = ReadInt(file); - int maxy = ReadInt(file); - unsigned char *background = ReadLine(file); - /*int backgroundx =*/ - ReadInt(file); //avoid warnings: unused variable - /*int backgroundy =*/ - ReadInt(file); - /*unsigned char red =*/ - ReadByte(file); - /*unsigned char green =*/ - ReadByte(file); - /*unsigned char blue =*/ - ReadByte(file); - unsigned char *mapcheck = ReadLine(file); - //----------------------------------------- - unsigned char *tilemode = malloc(loaded + 1); - if (tilemode == NULL) - error_exit("Memory error in ReadMap()\n"); - for (i = 0; i <= loaded; i++) - { - tilemode[i] = ReadByte(file); - } - - map = malloc(maxx * sizeof(struct TILE *)); - if (map == NULL) - error_exit("Memory error in ReadMap()\n"); - for (i = 0; i <= maxx; i++) - { - map[i] = malloc(maxy * sizeof(struct TILE *)); - if (map[i] == NULL) - error_exit("Memory error in ReadMap()\n"); - int b; - for (b = 0; b <= maxy; b++) - { - unsigned char bytecache = ReadByte(file); - if (bytecache > loaded) - { - bytecache = 0; - } - map[i][b].tileid = bytecache; - map[i][b].mode = tilemode[bytecache]; - //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); - } - } - //--------------------------------------- - unsigned char enities_count = ReadByte(file); - for (i = 0; i <= enities_count - 1; i++) - { - unsigned char *name = ReadLine(file); - unsigned char typ = ReadByte(file); - int x = ReadInt(file); - int y = ReadInt(file); - unsigned char *trigger = ReadLine(file); - - //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); - int b; - for (b = 0; b <= 9; b++) - { - /*int unknownint =*/ReadInt(file); - unsigned char *unknown = ReadLine(file); - //eprintf("(%d) %s || ", unknownint, unknown); - free(unknown); - } - - switch (typ) - { - case 0: - { - tspawnx[tspawncount] = x; - tspawny[tspawncount] = y; - tspawncount++; - break; - } - case 1: - { - ctspawnx[ctspawncount] = x; - ctspawny[ctspawncount] = y; - ctspawncount++; - break; - } - default: - { - break; - } - } - free(name); - free(trigger); - } - - fclose(file); - - eprintf("loaded!\n"); - free(mapheader); - free(code); - free(tileset); - free(background); - free(mapcheck); -} - -/** - * \fn unsigned char *ReadLine(FILE *file) - * \brief read from a file stream a cs2d line (ends with \r\n; windows end) - * \param *file the file stream - * \return a pointer to the read line - */ -unsigned char *ReadLine(FILE *file) -{ - int position = 0; - char *line = NULL; - char c; - while ((c = fgetc(file)) != 13) - { - if (c == EOF) - error_exit("EndOfFile in ReadByte()\n"); - - line = realloc(line, position + 1); - if (line == NULL) - error_exit("Memory error in ReadLine()\n"); - - line[position] = c; - - position++; - } - - line = realloc(line, position + 1); - if (line == NULL) - error_exit("Memory error in ReadLine()\n"); - line[position] = '\0'; - position++; - - fgetc(file); //0x0A - - return (unsigned char*) line; -} - -/** - * \fn unsigned char ReadByte(FILE *file) - * \brief read from a file stream a byte - * \param *file the file stream - * \return the read byte - */ -unsigned char ReadByte(FILE *file) -{ - unsigned char byte = fgetc(file); - if (byte == EOF) - error_exit("EndOfFile in ReadByte()\n"); - return byte; -} -/** - * \fn int ReadInt(FILE *file) - * \brief read from a file stream a integer - * \param *file the file stream - * \return the read integer - */ -int ReadInt(FILE *file) -{ - unsigned char byte1 = fgetc(file); - if (byte1 == EOF) - error_exit("EndOfFile in ReadInt()\n"); - - unsigned char byte2 = fgetc(file); - if (byte2 == EOF) - error_exit("EndOfFile in ReadInt()\n"); - - unsigned char byte3 = fgetc(file); - if (byte3 == EOF) - error_exit("EndOfFile in ReadInt()\n"); - - unsigned char byte4 = fgetc(file); - if (byte4 == EOF) - error_exit("EndOfFile in ReadInt()\n"); - - return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; -} - +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/map.h" + +/** + * \fn void ReadMap() + * \brief reads the map and put all needed information into a variable + * needed: tspawn and ctspawn + */ +void ReadMap() +{ + FILE *file; + int i; + tspawncount = 0; + ctspawncount = 0; + + char *mappath = malloc(u_strlen(sv_map) + 5); + memcpy(mappath, sv_map, u_strlen(sv_map)); + memcpy(mappath + u_strlen(sv_map), ".map\0", 5); + + file = fopen(mappath, "rb"); + if (file == NULL) + error_exit("Map not found.. Abort\n"); + else printf("Loading '%s'..", mappath); + + free(mappath); + + //------------------------------ + unsigned char *mapheader = ReadLine(file); + for (i = 1; i <= 9; i++) + ReadByte(file); + for (i = 1; i <= 10; i++) + ReadInt(file); + for (i = 1; i <= 10; i++) + ReadLine(file); + unsigned char *code = ReadLine(file); + unsigned char *tileset = ReadLine(file); + unsigned char loaded = ReadByte(file); + int maxx = ReadInt(file); + int maxy = ReadInt(file); + unsigned char *background = ReadLine(file); + /*int backgroundx =*/ + ReadInt(file); //avoid warnings: unused variable + /*int backgroundy =*/ + ReadInt(file); + /*unsigned char red =*/ + ReadByte(file); + /*unsigned char green =*/ + ReadByte(file); + /*unsigned char blue =*/ + ReadByte(file); + unsigned char *mapcheck = ReadLine(file); + //----------------------------------------- + unsigned char *tilemode = malloc(loaded + 1); + if (tilemode == NULL) + error_exit("Memory error in ReadMap()\n"); + for (i = 0; i <= loaded; i++) + { + tilemode[i] = ReadByte(file); + } + + map = malloc(maxx * sizeof(struct TILE *)); + if (map == NULL) + error_exit("Memory error in ReadMap()\n"); + for (i = 0; i <= maxx; i++) + { + map[i] = malloc(maxy * sizeof(struct TILE *)); + if (map[i] == NULL) + error_exit("Memory error in ReadMap()\n"); + int b; + for (b = 0; b <= maxy; b++) + { + unsigned char bytecache = ReadByte(file); + if (bytecache > loaded) + { + bytecache = 0; + } + map[i][b].tileid = bytecache; + map[i][b].mode = tilemode[bytecache]; + //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); + } + } + //--------------------------------------- + unsigned char enities_count = ReadByte(file); + for (i = 0; i <= enities_count - 1; i++) + { + unsigned char *name = ReadLine(file); + unsigned char typ = ReadByte(file); + int x = ReadInt(file); + int y = ReadInt(file); + unsigned char *trigger = ReadLine(file); + + //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); + int b; + for (b = 0; b <= 9; b++) + { + /*int unknownint =*/ReadInt(file); + unsigned char *unknown = ReadLine(file); + //eprintf("(%d) %s || ", unknownint, unknown); + free(unknown); + } + + switch (typ) + { + case 0: + { + tspawnx[tspawncount] = x; + tspawny[tspawncount] = y; + tspawncount++; + break; + } + case 1: + { + ctspawnx[ctspawncount] = x; + ctspawny[ctspawncount] = y; + ctspawncount++; + break; + } + default: + { + break; + } + } + free(name); + free(trigger); + } + + fclose(file); + + eprintf("loaded!\n"); + free(mapheader); + free(code); + free(tileset); + free(background); + free(mapcheck); +} + +/** + * \fn unsigned char *ReadLine(FILE *file) + * \brief read from a file stream a cs2d line (ends with \r\n; windows end) + * \param *file the file stream + * \return a pointer to the read line + */ +unsigned char *ReadLine(FILE *file) +{ + int position = 0; + char *line = NULL; + char c; + while ((c = fgetc(file)) != 13) + { + if (c == EOF) + error_exit("EndOfFile in ReadByte()\n"); + + line = realloc(line, position + 1); + if (line == NULL) + error_exit("Memory error in ReadLine()\n"); + + line[position] = c; + + position++; + } + + line = realloc(line, position + 1); + if (line == NULL) + error_exit("Memory error in ReadLine()\n"); + line[position] = '\0'; + position++; + + fgetc(file); //0x0A + + return (unsigned char*) line; +} + +/** + * \fn unsigned char ReadByte(FILE *file) + * \brief read from a file stream a byte + * \param *file the file stream + * \return the read byte + */ +unsigned char ReadByte(FILE *file) +{ + unsigned char byte = fgetc(file); + if (byte == EOF) + error_exit("EndOfFile in ReadByte()\n"); + return byte; +} +/** + * \fn int ReadInt(FILE *file) + * \brief read from a file stream a integer + * \param *file the file stream + * \return the read integer + */ +int ReadInt(FILE *file) +{ + unsigned char byte1 = fgetc(file); + if (byte1 == EOF) + error_exit("EndOfFile in ReadInt()\n"); + + unsigned char byte2 = fgetc(file); + if (byte2 == EOF) + error_exit("EndOfFile in ReadInt()\n"); + + unsigned char byte3 = fgetc(file); + if (byte3 == EOF) + error_exit("EndOfFile in ReadInt()\n"); + + unsigned char byte4 = fgetc(file); + if (byte4 == EOF) + error_exit("EndOfFile in ReadInt()\n"); + + return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; +} + diff --git a/src/pakets.c b/src/pakets.c index 9415ed3..38b54f2 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -1,1707 +1,1750 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/pakets.h" - -/** - * \fn int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) - * \brief every unknown packet lands here - * \param *message pointer to the unknown message - * \param length sizeof message - * \param *buffer pointer to the udp-packet - * \param size sizeof buffer - * \param position where the unknown message in buffer begins - * \return read bytes (specific: parameter length) - */ -int unknown(unsigned char *message, int length, unsigned char *buffer, - int size, int position) -{ - int paketlength = length; - int i; - printf("Unknown packet: "); - for (i = 2; i <= position - 1; i++) - { - eprintf("%d-", buffer[i]); - } - eprintf("\n\t"); - for (i = 0; i <= length - 1; i++) - { - eprintf("%d-", message[i]); - } - eprintf("\n"); - return paketlength; -} - -/** - * \fn int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) - * \brief handles a connection setup for unknown player - * \param *message pointer to the unknown message - * \param length sizeof message - * \param ip clients ip - * \param port clients port - * \return read bytes (specific: 3) - */ -int connection_setup_unknown(unsigned char *message, int length, - struct in_addr ip, unsigned short port) -{ - int paketlength = 3; - if (length < paketlength) - { - printf("Invalid packet (connection_setup_unknown)!\n"); - return length; - } - return paketlength; -} - -/** - * \fn int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port) - * \brief handles a connection setup for known player - * \param *message pointer to the unknown message - * \param length sizeof message - * \param ip clients ip - * \param port clients port - * \return read bytes (specific: 3) - */ -int connection_setup_known(unsigned char *message, int length, - struct in_addr ip, unsigned short port, int id) -{ - int paketlength = 3; - if (length < paketlength) - { - printf("Invalid packet (connection_setup_known)!\n"); - return length; - } - - return paketlength; -} - -/** - * \fn int ping_ingame(unsigned char *message, int length, int id, int writesocket) - * \brief handles a answer from the server ingame ping. this function calculates the latency - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 5) - */ -int ping_ingame(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 5; - if (length < paketlength) - { - printf("Invalid packet (ping_ingame)!\n"); - return length; - } - player[id].latency = mtime() - player[id].start; - //printf("%s: %d\n", player[id].name, player[id].latency); - return paketlength; -} - -/** - * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) - * \brief handles a confirmation for unknown player - * \param *message pointer to the unknown message - * \param length sizeof message - * \param ip clients ip - * \param port clients port - * \return read bytes (specific: 3) - */ -int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, - unsigned short port) -{ - int paketlength = 3; - if (length < paketlength) - { - printf("Invalid packet (confirmation_unknown)!\n"); - return length; - } - - return paketlength; -} - -/** - * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) - * \brief handles a confirmation for known player - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 3) - */ -int confirmation_known(unsigned char *message, int length, int id, - int writesocket) -{ - int paketlength = 3; - if (length < paketlength) - { - printf("Invalid packet (confirmation_known)!\n"); - return length; - } - return paketlength; -} - -/** - * \fn int fire(unsigned char *message, int length, int id, int writesocket) - * \brief handles a fire - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 1) - */ -int fire(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 1; - if (length < paketlength) - { - printf("Invalid packet (fire)!\n"); - return length; - } - switch (OnFire(id, writesocket)) - { - case 0: - SendFireMessage(id, writesocket); - break; - case 1: - break; - } - return paketlength; -} - -/** - * \fn int advanced_fire(unsigned char *message, int length, int id, int writesocket) - * \brief handles a advanced_fire (right click) - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 1) - */ -int advanced_fire(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 2; - if (length < paketlength) - { - printf("Invalid packet (advanced_fire)!\n"); - return length; - } - unsigned int status = message[1]; - - switch (OnAdvancedFire(id, status, writesocket)) - { - case 0: - SendAdvancedFireMessage(id, status, writesocket); - break; - case 1: - break; - } - return paketlength; -} - -/** - * \fn int buy(unsigned char *message, int length, int id, int writesocket) - * \brief handles a buy request - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 3) - */ -int buy(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 3; - if (length < paketlength) - { - printf("Invalid packet (buy)!\n"); - return length; - } - - int position = 1; - int wpnid; - - wpnid = message[position]; - position++; - - switch (OnBuyAttempt(id, wpnid, writesocket)) - { - case 0: - OnBuy(id, wpnid, writesocket); - SendBuyMessage(id, wpnid, writesocket); - break; - case 1: - break; - } - return paketlength; -} - -/** - * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) - * \brief handles a rotation update - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 5) - */ -int rotupdate(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 5; - float temprotation; - if (length < paketlength) - { - printf("Invalid packet (rot_update)!\n"); - return length; - } - memcpy(&temprotation, message + 1, sizeof(float)); - if (temprotation >= -180 && temprotation <= 180) - { - //if(temprotation < 0) temprotation += 360; - memcpy(&player[id].rotation, &temprotation, sizeof(float)); - SendRotUpdate(id, player[id].rotation, writesocket); - } - return paketlength; -} - -/** - * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) - * \brief handles a position walk update - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 5) - */ -int posupdatewalk(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 5; - unsigned short tempx; - unsigned short tempy; - if (length < paketlength) - { - printf("Invalid packet (posupdatewalk)!\n"); - return length; - } - memcpy(&tempx, message + 1, 2); - memcpy(&tempy, message + 3, 2); - switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) - { - case 0: - SendPosUpdate(id, tempx, tempy, 0, writesocket); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); - break; - default: - break; - } - return paketlength; -} -/** - * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) - * \brief handles a position run update - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 5) - */ -int posupdaterun(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 5; - unsigned short tempx; - unsigned short tempy; - if (length < paketlength) - { - printf("Invalid packet (posupdaterun)!\n"); - return length; - } - memcpy(&tempx, message + 1, 2); - memcpy(&tempy, message + 3, 2); - switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) - { - case 0: - SendPosUpdate(id, tempx, tempy, 1, writesocket); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); - break; - default: - break; - } - return paketlength; -} -/** - * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) - * \brief handles a position walk and rotation update - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 9) - */ -int posrotupdatewalk(unsigned char *message, int length, int id, - int writesocket) -{ - int paketlength = 9; - unsigned short tempx; - unsigned short tempy; - float rotation; - if (length < paketlength) - { - printf("Invalid packet (posrotupdatewalk)!\n"); - return length; - } - memcpy(&tempx, message + 1, 2); - memcpy(&tempy, message + 3, 2); - memcpy(&rotation, message + 5, sizeof(float)); - - if (rotation >= -180 && rotation <= 180) - { - switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) - { - case 0: - //if(rotation < 0) rotation += 360; - SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); - memcpy(&player[id].rotation, &rotation, sizeof(float)); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosRotUpdate(id, player[id].x, player[id].y, 0, - player[id].rotation, writesocket); - break; - default: - break; - } - } - return paketlength; -} - -/** - * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) - * \brief handles a position run and rotation update - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 9) - */ -int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 9; - unsigned short tempx; - unsigned short tempy; - float rotation; - if (length < paketlength) - { - printf("Invalid packet (posrotupdatewalk)!\n"); - return length; - } - memcpy(&tempx, message + 1, 2); - memcpy(&tempy, message + 3, 2); - memcpy(&rotation, message + 5, sizeof(float)); - - if (rotation >= -180 && rotation <= 180) - { - switch (OnMoveAttempt(id, tempx, tempy, 1, writesocket)) - { - case 0: - //if(rotation < 0) rotation += 360; - SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); - memcpy(&player[id].rotation, &rotation, sizeof(float)); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosRotUpdate(id, player[id].x, player[id].y, 1, - player[id].rotation, writesocket); - break; - default: - break; - } - } - return paketlength; -} - -/** - * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) - * \brief handles a respawn request - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 1) - */ -int respawnrequest(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 1; - if (length < paketlength) - { - printf("Invalid packet (respawnrequest)! (WTF?)\n"); - return length; - } - switch (OnRespawnRequest(id, writesocket)) - { - case 0: - srand(time(NULL)); - switch (player[id].team) - { - case 0: - printf("%s tried to spawn as spectator!\n", player[id].name); - break; - case 1: - { - int tmp = rand() % tspawncount; - printf("%s spawned!\n", player[id].name); - player[id].health = 100; - player[id].dead = 0; - player[id].x = (tspawnx[tmp] + 0.5) * 32; - player[id].y = (tspawny[tmp] + 0.5) * 32; - SendSpawnMessage(id, player[id].x, player[id].y, writesocket); - break; - } - case 2: - { - int tmp = rand() % ctspawncount; - printf("%s spawned!\n", player[id].name); - player[id].health = 100; - player[id].dead = 0; - player[id].x = (ctspawnx[tmp] + 0.5) * 32; - player[id].y = (ctspawny[tmp] + 0.5) * 32; - SendSpawnMessage(id, player[id].x, player[id].y, writesocket); - break; - } - - } - break; - case 1: - break; - default: - break; - } - return paketlength; -} -/** - * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) - * \brief handles a weapon change - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 3) - */ -int weaponchange(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 3; - if (length < paketlength) - { - printf("Invalid packet (weaponchange)!\n"); - return length; - } - int position = 1; - int wpnid; - - wpnid = message[position]; - position++; - - switch (OnWeaponChangeAttempt(id, wpnid, writesocket)) - { - case 0: - SendWeaponChangeMessage(id, wpnid, writesocket); - break; - case 1: - break; - default: - break; - } - return paketlength; -} - -/** - * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) - * \brief handles a team change - * \param *message pointer to the message - * \param length sizeof message - * \param id clients player id - * \param writesocket the socket where it was read - * \return read bytes (specific: 3) - */ -int teamchange(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 3; - if (length < paketlength) - { - printf("Invalid packet (teamchange)!\n"); - return length; - } - unsigned char team = message[1]; - unsigned char skin = message[2]; - - switch (OnTeamChangeAttempt(id, team, skin, writesocket)) - { - case 0: - player[id].team = team; - if (skin != 5) - player[id].skin = skin; - OnTeamChange(id, team, skin, writesocket); - break; - case 1: - break; - default: - break; - } - return paketlength; -} -/** - * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) - * \brief handles a team change - * \param *message pointer to the message - * \param length sizeof message - * \param *client pointer to the client information structure - * \param writesocket the socket where it was read - * \return read bytes (specific: 5) - */ -int ping_serverlist(unsigned char *message, int length, - struct sockaddr_in *client, int writesocket) -{ - int paketlength = 5; - if (length < paketlength) - { - printf("Invalid packet (ping_serverlist)!\n"); - return length; - } - - unsigned char *tempbuffer = malloc(paketlength); - if (tempbuffer == NULL) - error_exit("Memory error ( ping_serverlist() )"); - - tempbuffer[0] = 0x01; - tempbuffer[1] = 0x00; - memcpy(tempbuffer + 2, message, paketlength); - - udp_send(writesocket, tempbuffer, 5, client); - free(tempbuffer); - return paketlength; -} - -int serverinfo_request(unsigned char *message, int length, - struct sockaddr_in *client, int writesocket) -{ - int paketlength = length; - if (length < 2) - { - printf("Invalid packet (serverinfo_request)!\n"); - return length; - } - - /* - int i; - printf("serverinfo_request (%d): ", message[0]); - for (i = 1; i <= paketlength; i++) - { - printf("%d-", message[i]); - } - printf("(%d)\n", paketlength); - int joinroutine_known(unsigned char *message, int length, int id, int writesocket) - */ - - int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); - if (sv_gamemode != 0) - { - stringsize++; - } - - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( serverinfo_request() )"); - - int position = 0; - buffer[position] = 1; - position++; - buffer[position] = 0; - position++; - buffer[position] = 0xFB; - position++; - buffer[position] = message[1]; - position++; - - switch (message[1]) - { - case 1: - case 2: - /* - if(message[2] == 0) - { - paketlength = 2; - } - else - { - paketlength = 6; - } - */ - paketlength = 4; - - buffer[position] = GetServerStatus(); - position++; - buffer[position] = u_strlen(sv_name); - position++; - memcpy(buffer + position, sv_name, u_strlen(sv_name)); - position += u_strlen(sv_name); - buffer[position] = u_strlen(sv_map); - position++; - memcpy(buffer + position, sv_map, u_strlen(sv_map)); - position += u_strlen(sv_map); - buffer[position] = onlineplayer; - position++; - buffer[position] = sv_maxplayers; - position++; - if (sv_gamemode != 0) - { - buffer[position] = sv_gamemode; - position++; - } - buffer[position] = bot_count; - position++; - udp_send(writesocket, buffer, stringsize, client); - break; - case 4: - break; - case 5: - break; - default: - break; - } - - free(buffer); - - return paketlength; -} - -int joinroutine_unknown(unsigned char *message, int length, - struct sockaddr_in *client, int writesocket) -{ - int paketlength = length; //Just 2 char read (message[1]) - if (length < 2) - { - printf("Invalid packet (joinroutine_unknown)!\n"); - return length; - } - switch (message[1]) - { - case 0x00: - { - paketlength = 2; - - int i; - for (i = 1; i <= MAX_CLIENTS - 1; i++) - { - if (player[i].used != 1) - { - player[i].used = 1; - player[i].ip = client->sin_addr; - player[i].port = client->sin_port; - player[i].joinstatus = 1; - player[i].client_nummer = 4; - player[i].server_nummer = 2; - break; - } - } - int stringsize = 5 + u_strlen(pre_authcode); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_unknown() )"); - - int position = 0; - buffer[position] = 0x01; - position++; - buffer[position] = 0x00; - position++; - buffer[position] = 0xFC; - position++; - buffer[position] = 0x00; - position++; - buffer[position] = u_strlen(pre_authcode); - position++; - memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); - - udp_send(writesocket, buffer, stringsize, client); - - free(buffer); - break; - } - default: - printf("Unexpected join data (%d)\n", message[0]); - break; - } - - return paketlength; -} - -int specpos(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 9; - if (paketlength > length) - { - printf("Invalid packet (specpos)!\n"); - return length; - } - int x, y; - - x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) - | message[1]; - y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) - | message[5]; - - switch (OnSpecmove(id, x, y, writesocket)) - { - case 0: - { - player[id].specposx = x; - player[id].specposy = y; - break; - } - case 1: - { - break; - } - } - return paketlength; -} - -int chatmessage(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 4; - unsigned char team, unknown; - int paketsize; - - if (paketlength > length) - { - printf("Invalid packet (chatmessage)!\n"); - return length; - } - - int position = 0; - position++; - team = message[position]; - position++; - - paketsize = message[position]; - if (paketsize > 255 || paketsize >= (length - position + 1)) - { - printf("Message too big\n"); - return length; - } - position++; - paketlength += paketsize; - - unknown = message[position]; - position++; - - unsigned char *string = malloc(paketsize); - if (string == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(string, message + position, paketsize); - string[paketsize] = '\0'; - position += paketsize; - - switch (OnChatMessage(id, string, team, writesocket)) - { - case 0: - break; - default: - printf("Unknown Return value for OnChatMessage()!\n"); - break; - } - - free(string); - - return paketlength; -} - -int joinroutine_known(unsigned char *message, int length, int id, - int writesocket) -{ - int paketlength = 2; - if (paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - switch (message[1]) - { - case 0: - { - paketlength = 2; - if (paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - break; - } - case 1: - { - if (player[id].joinstatus == 1) - { - paketlength = 16; // ??? - if (paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - - int position = 2; - //Playername - int stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("Playername too big\n"); - return length; - } - paketlength += stringsize; - position++; - - player[id].name = malloc(stringsize); - if (player[id].name == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].name, message + position, stringsize); - player[id].name[stringsize] = '\0'; - position += stringsize; //+1 because after it there is a null byte, so ignore it - - //printf("Player %s connected..\n", player[id].name); - - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("Password too big\n"); - return length; - } - paketlength += stringsize; - position++; - - unsigned char *password = malloc(stringsize); - if (password == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(password, message + position, stringsize); - password[stringsize] = '\0'; - position += stringsize; - - //printf("\tPassword: "); - /* - int i; - for (i = 0; i <= u_strlen(password); i++) - { - printf("%d-", password[i]); - } - printf("\n"); - */ - - //Encryption String - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("Encryption too big\n"); - return length; - } - paketlength += stringsize; - position++; - - unsigned char *encryption1 = malloc(stringsize); - if (encryption1 == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(encryption1, message + position, stringsize); - encryption1[stringsize] = '\0'; - position += stringsize; - - //printf("\tEncryptionstring: %s\n", encryption1); - - //Player Version - player[id].version = message[position]; - position++; - //printf("\tVersion: %d\n", player[id].version); - position++; //Null-byte - - - //USGN ID - player[id].usgn = malloc(sizeof(unsigned short)); - if (player[id].usgn == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].usgn, message + position, 2); //sizeof(unsigned short) == 2 - position += 4; //2 bytes + 2 null bytes - /* - #else - *player[id].usgn = endian_swap_short(player[id].usgn); - #endif - */ - //printf("\tUSGN-ID: %u\n", *player[id].usgn); - - - //Spraylogo - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("Spraylogoname too big\n"); - return length; - }; - paketlength += stringsize; - position++; - - player[id].spraylogo = malloc(stringsize); - if (player[id].spraylogo == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].spraylogo, message + position, stringsize); - player[id].spraylogo[stringsize] = '\0'; - position += stringsize; - - //printf("\tSpraylogo: %s\n", player[id].spraylogo); - - - //Map-Hash - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("Map-Hash too big\n"); - return length; - } - paketlength += stringsize; - position++; - - unsigned char *maphash = malloc(stringsize); - if (maphash == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(maphash, message + position, stringsize); - maphash[stringsize] = '\0'; - position += stringsize; - - //printf("\tMap-Hash: %s\n", maphash); - - position++; //Nullbyte - - //WIN - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("WIN too big\n"); - return length; - } - paketlength += stringsize; - position++; - - player[id].win = malloc(stringsize); - if (player[id].win == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].win, message + position, stringsize); - player[id].win[stringsize] = '\0'; - position += stringsize; - - //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); - - unsigned char *buffer = NULL; - stringsize = 0; - int tempstatus = CheckPlayerData(password); - switch (tempstatus) - { - case 0x00: - stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 2; - position++; - buffer[position] = 0; //Normal - position++; - buffer[position] = id; - position++; - buffer[position] = u_strlen(sv_map); - position++; - memcpy(buffer + position, sv_map, u_strlen(sv_map)); - position += u_strlen(sv_map); - buffer[position] = u_strlen(pre_authcode); - position++; - memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); - position += u_strlen(pre_authcode); - player[id].joinstatus = 2; - break; - - default: - { - stringsize = 3; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 2; - position++; - buffer[position] = tempstatus; //Everyone is banned (just for testing) - position++; - player[id].joinstatus = 0; - break; - } - - } - //stringsize = 16 + u_strlen(sv_map); - - /* - 0 - Normal - 1 - Password wrong - 2 - USGN only - 3 - Server full - 4 - Banned - 5 - Another Game Version - 6 - ?? - 7 - Can't validate user (USGN offline) - 8 - ?? - 9 - Connection already exists - 10 - Wrong client (pre_authcode) - 11 - Diffrent map (temp, etc.) - 12 - Map unknown (maptransfer disabled) - 13++ - Failed to join - */ - - if (stringsize != 0) - SendToPlayer(buffer, stringsize, id, 1, writesocket); - - free(encryption1); - free(maphash); - free(buffer); - - onlineplayer++; - } - else - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - case 3: - { - if (player[id].joinstatus == 2) - { - int position = 2; - - paketlength = 5; - if (paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - - //Map-Hash - int stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("Map-Hash too big\n"); - return length; - } - position++; - - unsigned char *maphash = malloc(stringsize); - if (maphash == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(maphash, message + position, stringsize); - maphash[stringsize] = '\0'; - position += stringsize; - paketlength += stringsize; - - //printf("\tMaphash: %s\n", maphash); - - //pre_authcode_respond - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("pre_authcon_respond too big\n"); - return length; - } - position++; - - unsigned char *pre_authcode_respond = malloc(stringsize); - if (pre_authcode_respond == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(pre_authcode_respond, message + position, stringsize); - pre_authcode_respond[stringsize] = '\0'; - position += stringsize; - paketlength += stringsize; - - //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); - - //Player Version - //unsigned char mapstatus = message[position]; //avoid warning - position++; - //printf("\tMapstatus: %d\n", mapstatus); - - free(pre_authcode_respond); - free(maphash); - - //Respond - stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 4; - position++; - buffer[position] = 0; //CheckPlayerData() - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - player[id].joinstatus = 3; - } - else - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - case 5: - { - if (player[id].joinstatus == 3) - { - int position = 2; - - paketlength = 3; - if (paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - //Map-Hash - int stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length - position + 1)) - { - printf("Mapname too big\n"); - return length; - } - position++; - - unsigned char *mapname = malloc(stringsize); - if (mapname == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(mapname, message + position, stringsize); - mapname[stringsize] = '\0'; - position += stringsize; - paketlength += stringsize; - - //printf("\tMapname: %s\n", mapname); - - - //----------- ServerData ----------- - - stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 6; - position++; - buffer[position] = 0; //CheckPlayerData() - position++; - - buffer[position] = u_strlen(sv_map); - position++; - memcpy(buffer + position, sv_map, u_strlen(sv_map)); - position += u_strlen(sv_map); - - buffer[position] = u_strlen(sv_name); - position++; - memcpy(buffer + position, sv_name, u_strlen(sv_name)); - position += u_strlen(sv_name); - - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = sv_friendlyfire; - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = mp_roundtime; - position++; - buffer[position] = mp_freezetime; - position++; - buffer[position] = mp_c4timer; - position++; - buffer[position] = 32; //Unknown - position++; - buffer[position] = 124; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 1; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = sv_maxplayers; - position++; - buffer[position] = sv_fow; - position++; - buffer[position] = mp_specmode; - position++; - buffer[position] = sv_gamemode; - position++; - buffer[position] = mp_respawndelay; - position++; - buffer[position] = mp_infammo; - position++; - buffer[position] = 3; //u_strlen ACK - position++; - buffer[position] = 65; //A - position++; - buffer[position] = 67; //C - position++; - buffer[position] = 75; //K - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- PlayerData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 1; - position++; - buffer[position] = onlineplayer; - position++; - - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && player[i].joinstatus >= 1 && i != id) - { - unsigned char *encodedname; - encodedname = GetEncodedString(player[i].name, u_strlen( - player[i].name)); - unsigned short *deaths = &player[i].deaths; - unsigned short tempscore = (unsigned) (player[i].deaths - + 1000); - unsigned short *score = &tempscore; - - unsigned short tempx = (player[i].x); - unsigned short tempy = (player[i].y); - unsigned short *x = &tempx; - unsigned short *y = &tempy; - - float *ptemprotation = &player[i].rotation; - - int playersize = 25 + u_strlen(encodedname); - buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - buffer[position] = i; - position++; - - buffer[position] = u_strlen(encodedname); - position++; - memcpy(buffer + position, encodedname, - u_strlen(encodedname)); - position += u_strlen(encodedname); - free(encodedname); - - buffer[position] = 0; //Unknown - position++; - buffer[position] = player[i].team; - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - /* - buffer[position] = score[0]; //Deaths - position++; - buffer[position] = score[1]; //Deaths - position++; - */ - memcpy(buffer + position, score, 2); - position += 2; - /* - buffer[position] = deaths[0]; //Deaths - position++; - buffer[position] = deaths[1]; //Deaths - position++; - */ - memcpy(buffer + position, deaths, 2); - position += 2; - memcpy(buffer + position, x, 2); - position += 2; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - memcpy(buffer + position, y, 2); - position += 2; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = ptemprotation[0]; //Rotation - position++; - buffer[position] = ptemprotation[1]; //Rotation - position++; - buffer[position] = player[i].health; //Health - position++; - buffer[position] = player[i].armor; //Armor - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] - = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe - position++; - buffer[position] = 0; //Unknown - position++; - /* - 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 - 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 - 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 - 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 - e8 03 00 00 12 01 00 00 01 03 - e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 - e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 - 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 - */ - } - } - if (1) - { - unsigned char *encodedname; - encodedname = GetEncodedString(player[id].name, u_strlen( - player[id].name)); - - int playersize = 25 + u_strlen(encodedname); - buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - buffer[position] = id; - position++; - - buffer[position] = u_strlen(encodedname); - position++; - memcpy(buffer + position, encodedname, u_strlen(encodedname)); - position += u_strlen(encodedname); - free(encodedname); - - buffer[position] = 0; //Unknown - position++; - buffer[position] = player[id].team; - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 232; //Unknown - position++; - buffer[position] = 3; //Unknown - position++; - buffer[position] = 0; //Deaths - position++; - buffer[position] = 0; //Deaths - position++; - buffer[position] = 0; //X - position++; - buffer[position] = 0; //X - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Y - position++; - buffer[position] = 0; //Y - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Health - position++; - buffer[position] = 0; //Armor - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Aktuelle Waffe 50 = Knife - position++; - buffer[position] = 0; //Unknown - position++; - } - - SendToPlayer(buffer, position, id, 1, writesocket); - free(buffer); - - //----------- PlayerData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 1; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- HostageData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 2; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- ItemData ----------- - - /* - fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 - */ - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 3; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- EnityData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 4; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- DynamicObjectData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 5; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- ProjectileData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 6; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- DynamicObjectImageData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 7; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- Final ACK ----------- - stringsize = 7; - buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 200; //third payload - position++; - buffer[position] = 3; //u_strlen ACK - position++; - buffer[position] = 65; //A - position++; - buffer[position] = 67; //C - position++; - buffer[position] = 75; //K - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - player[id].joinstatus = 4; - free(mapname); - - OnJoin(id, writesocket); - } - else - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - default: - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - - return paketlength; -} - -int leave(int id, int writesocket) -{ - OnLeave(id, writesocket); - - free(player[id].name); - free(player[id].usgn); - free(player[id].spraylogo); - free(player[id].win); - - player[id].name = NULL; - player[id].usgn = NULL; - player[id].spraylogo = NULL; - player[id].win = NULL; - - onlineplayer--; - - ClearPlayer(id); - - return 2; -} - -int reload(unsigned char *message, int length, int id, int writesocket) -{ - int paketlength = 2; - if (length < paketlength) - { - printf("Invalid packet (buy)!\n"); - return length; - } - - int position = 1; - int status; - - status = message[position]; - position++; - - if (status == 1) - { - SendReloadMessage(id, 1, writesocket); - player[id].reloading = player[id].actualweapon; - player[id].reloadtimer - = mtime() - + weapons[player[id].slot[player[id].actualweapon].id].reloadtime; - } - return paketlength; -} +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/pakets.h" + +/** + * \fn int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) + * \brief every unknown packet lands here + * \param *message pointer to the unknown message + * \param length sizeof message + * \param *buffer pointer to the udp-packet + * \param size sizeof buffer + * \param position where the unknown message in buffer begins + * \return read bytes (specific: parameter length) + */ +int unknown(unsigned char *message, int length, unsigned char *buffer, + int size, int position) +{ + int paketlength = length; + int i; + printf("Unknown packet: "); + for (i = 2; i <= position - 1; i++) + { + eprintf("%d-", buffer[i]); + } + eprintf("\n\t"); + for (i = 0; i <= length - 1; i++) + { + eprintf("%d-", message[i]); + } + eprintf("\n"); + return paketlength; +} + +/** + * \fn int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) + * \brief handles a connection setup for unknown player + * \param *message pointer to the unknown message + * \param length sizeof message + * \param ip clients ip + * \param port clients port + * \return read bytes (specific: 3) + */ +int connection_setup_unknown(unsigned char *message, int length, + struct in_addr ip, unsigned short port) +{ + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (connection_setup_unknown)!\n"); + return length; + } + return paketlength; +} + +/** + * \fn int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port) + * \brief handles a connection setup for known player + * \param *message pointer to the unknown message + * \param length sizeof message + * \param ip clients ip + * \param port clients port + * \return read bytes (specific: 3) + */ +int connection_setup_known(unsigned char *message, int length, + struct in_addr ip, unsigned short port, int id) +{ + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (connection_setup_known)!\n"); + return length; + } + + return paketlength; +} + +/** + * \fn int ping_ingame(unsigned char *message, int length, int id, int writesocket) + * \brief handles a answer from the server ingame ping. this function calculates the latency + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ +int ping_ingame(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + if (length < paketlength) + { + printf("Invalid packet (ping_ingame)!\n"); + return length; + } + player[id].latency = mtime() - player[id].start; + //printf("%s: %d\n", player[id].name, player[id].latency); + return paketlength; +} + +/** + * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) + * \brief handles a confirmation for unknown player + * \param *message pointer to the unknown message + * \param length sizeof message + * \param ip clients ip + * \param port clients port + * \return read bytes (specific: 3) + */ +int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, + unsigned short port) +{ + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (confirmation_unknown)!\n"); + return length; + } + + return paketlength; +} + +/** + * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) + * \brief handles a confirmation for known player + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ +int confirmation_known(unsigned char *message, int length, int id, + int writesocket) +{ + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (confirmation_known)!\n"); + return length; + } + return paketlength; +} + +/** + * \fn int fire(unsigned char *message, int length, int id, int writesocket) + * \brief handles a fire + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 1) + */ +int fire(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 1; + if (length < paketlength) + { + printf("Invalid packet (fire)!\n"); + return length; + } + switch (OnFire(id, writesocket)) + { + case 0: + SendFireMessage(id, writesocket); + break; + case 1: + break; + } + return paketlength; +} + +/** + * \fn int advanced_fire(unsigned char *message, int length, int id, int writesocket) + * \brief handles a advanced_fire (right click) + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 1) + */ +int advanced_fire(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 2; + if (length < paketlength) + { + printf("Invalid packet (advanced_fire)!\n"); + return length; + } + unsigned int status = message[1]; + + switch (OnAdvancedFire(id, status, writesocket)) + { + case 0: + SendAdvancedFireMessage(id, status, writesocket); + break; + case 1: + break; + } + return paketlength; +} + +/** + * \fn int buy(unsigned char *message, int length, int id, int writesocket) + * \brief handles a buy request + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ +int buy(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (buy)!\n"); + return length; + } + + int position = 1; + int wpnid; + + wpnid = message[position]; + position++; + + switch (OnBuyAttempt(id, wpnid, writesocket)) + { + case 0: + OnBuy(id, wpnid, writesocket); + SendBuyMessage(id, wpnid, writesocket); + break; + case 1: + break; + } + return paketlength; +} + +/** + * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) + * \brief handles a rotation update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ +int rotupdate(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + float temprotation; + if (length < paketlength) + { + printf("Invalid packet (rot_update)!\n"); + return length; + } + memcpy(&temprotation, message + 1, sizeof(float)); + if (temprotation >= -180 && temprotation <= 180) + { + //if(temprotation < 0) temprotation += 360; + memcpy(&player[id].rotation, &temprotation, sizeof(float)); + SendRotUpdate(id, player[id].rotation, writesocket); + } + return paketlength; +} + +/** + * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) + * \brief handles a position walk update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ +int posupdatewalk(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + unsigned short tempx; + unsigned short tempy; + if (length < paketlength) + { + printf("Invalid packet (posupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + SendPosUpdate(id, tempx, tempy, 0, writesocket); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); + break; + default: + break; + } + return paketlength; +} +/** + * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) + * \brief handles a position run update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ +int posupdaterun(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + unsigned short tempx; + unsigned short tempy; + if (length < paketlength) + { + printf("Invalid packet (posupdaterun)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + SendPosUpdate(id, tempx, tempy, 1, writesocket); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); + break; + default: + break; + } + return paketlength; +} +/** + * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) + * \brief handles a position walk and rotation update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 9) + */ +int posrotupdatewalk(unsigned char *message, int length, int id, + int writesocket) +{ + int paketlength = 9; + unsigned short tempx; + unsigned short tempy; + float rotation; + if (length < paketlength) + { + printf("Invalid packet (posrotupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + memcpy(&rotation, message + 5, sizeof(float)); + + if (rotation >= -180 && rotation <= 180) + { + switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + //if(rotation < 0) rotation += 360; + SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); + memcpy(&player[id].rotation, &rotation, sizeof(float)); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosRotUpdate(id, player[id].x, player[id].y, 0, + player[id].rotation, writesocket); + break; + default: + break; + } + } + return paketlength; +} + +/** + * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) + * \brief handles a position run and rotation update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 9) + */ +int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 9; + unsigned short tempx; + unsigned short tempy; + float rotation; + if (length < paketlength) + { + printf("Invalid packet (posrotupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + memcpy(&rotation, message + 5, sizeof(float)); + + if (rotation >= -180 && rotation <= 180) + { + switch (OnMoveAttempt(id, tempx, tempy, 1, writesocket)) + { + case 0: + //if(rotation < 0) rotation += 360; + SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); + memcpy(&player[id].rotation, &rotation, sizeof(float)); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosRotUpdate(id, player[id].x, player[id].y, 1, + player[id].rotation, writesocket); + break; + default: + break; + } + } + return paketlength; +} + +/** + * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) + * \brief handles a respawn request + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 1) + */ +int respawnrequest(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 1; + if (length < paketlength) + { + printf("Invalid packet (respawnrequest)! (WTF?)\n"); + return length; + } + switch (OnRespawnRequest(id, writesocket)) + { + case 0: + srand(time(NULL)); + switch (player[id].team) + { + case 0: + printf("%s tried to spawn as spectator!\n", player[id].name); + break; + case 1: + { + int tmp = rand() % tspawncount; + printf("%s spawned!\n", player[id].name); + player[id].health = 100; + player[id].dead = 0; + player[id].x = (tspawnx[tmp] + 0.5) * 32; + player[id].y = (tspawny[tmp] + 0.5) * 32; + SendSpawnMessage(id, player[id].x, player[id].y, writesocket); + break; + } + case 2: + { + int tmp = rand() % ctspawncount; + printf("%s spawned!\n", player[id].name); + player[id].health = 100; + player[id].dead = 0; + player[id].x = (ctspawnx[tmp] + 0.5) * 32; + player[id].y = (ctspawny[tmp] + 0.5) * 32; + SendSpawnMessage(id, player[id].x, player[id].y, writesocket); + break; + } + + } + break; + case 1: + break; + default: + break; + } + return paketlength; +} +/** + * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) + * \brief handles a weapon change + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ +int weaponchange(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (weaponchange)!\n"); + return length; + } + int position = 1; + int wpnid; + + wpnid = message[position]; + position++; + + switch (OnWeaponChangeAttempt(id, wpnid, writesocket)) + { + case 0: + SendWeaponChangeMessage(id, wpnid, writesocket); + break; + case 1: + break; + default: + break; + } + return paketlength; +} + +/** + * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) + * \brief handles a team change + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ +int teamchange(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (teamchange)!\n"); + return length; + } + unsigned char team = message[1]; + unsigned char skin = message[2]; + + switch (OnTeamChangeAttempt(id, team, skin, writesocket)) + { + case 0: + player[id].team = team; + if (skin != 5) + player[id].skin = skin; + OnTeamChange(id, team, skin, writesocket); + break; + case 1: + break; + default: + break; + } + return paketlength; +} +/** + * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) + * \brief handles a team change + * \param *message pointer to the message + * \param length sizeof message + * \param *client pointer to the client information structure + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ +int ping_serverlist(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket) +{ + int paketlength = 5; + if (length < paketlength) + { + printf("Invalid packet (ping_serverlist)!\n"); + return length; + } + + unsigned char *tempbuffer = malloc(paketlength); + if (tempbuffer == NULL) + error_exit("Memory error ( ping_serverlist() )"); + + tempbuffer[0] = 0x01; + tempbuffer[1] = 0x00; + memcpy(tempbuffer + 2, message, paketlength); + + udp_send(writesocket, tempbuffer, 5, client); + free(tempbuffer); + return paketlength; +} + +int serverinfo_request(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket) +{ + int paketlength = length; + if (length < 2) + { + printf("Invalid packet (serverinfo_request)!\n"); + return length; + } + + /* + int i; + printf("serverinfo_request (%d): ", message[0]); + for (i = 1; i <= paketlength; i++) + { + printf("%d-", message[i]); + } + printf("(%d)\n", paketlength); + int joinroutine_known(unsigned char *message, int length, int id, int writesocket) + */ + + int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); + if (sv_gamemode != 0) + { + stringsize++; + } + + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( serverinfo_request() )"); + + int position = 0; + buffer[position] = 1; + position++; + buffer[position] = 0; + position++; + buffer[position] = 0xFB; + position++; + buffer[position] = message[1]; + position++; + + switch (message[1]) + { + case 1: + case 2: + /* + if(message[2] == 0) + { + paketlength = 2; + } + else + { + paketlength = 6; + } + */ + paketlength = 4; + + buffer[position] = GetServerStatus(); + position++; + buffer[position] = u_strlen(sv_name); + position++; + memcpy(buffer + position, sv_name, u_strlen(sv_name)); + position += u_strlen(sv_name); + buffer[position] = u_strlen(sv_map); + position++; + memcpy(buffer + position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); + buffer[position] = onlineplayer; + position++; + buffer[position] = sv_maxplayers; + position++; + if (sv_gamemode != 0) + { + buffer[position] = sv_gamemode; + position++; + } + buffer[position] = bot_count; + position++; + udp_send(writesocket, buffer, stringsize, client); + break; + case 4: + break; + case 5: + break; + default: + break; + } + + free(buffer); + + return paketlength; +} + +int joinroutine_unknown(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket) +{ + int paketlength = length; //Just 2 char read (message[1]) + if (length < 2) + { + printf("Invalid packet (joinroutine_unknown)!\n"); + return length; + } + switch (message[1]) + { + case 0x00: + { + paketlength = 2; + + int i; + for (i = 1; i <= MAX_CLIENTS - 1; i++) + { + if (player[i].used != 1) + { + player[i].used = 1; + player[i].ip = client->sin_addr; + player[i].port = client->sin_port; + player[i].joinstatus = 1; + player[i].client_nummer = 4; + player[i].server_nummer = 2; + break; + } + } + int stringsize = 5 + u_strlen(pre_authcode); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_unknown() )"); + + int position = 0; + buffer[position] = 0x01; + position++; + buffer[position] = 0x00; + position++; + buffer[position] = 0xFC; + position++; + buffer[position] = 0x00; + position++; + buffer[position] = u_strlen(pre_authcode); + position++; + memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); + + udp_send(writesocket, buffer, stringsize, client); + + free(buffer); + break; + } + default: + printf("Unexpected join data (%d)\n", message[0]); + break; + } + + return paketlength; +} + +int specpos(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 9; + if (paketlength > length) + { + printf("Invalid packet (specpos)!\n"); + return length; + } + int x, y; + + x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) + | message[1]; + y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) + | message[5]; + + switch (OnSpecmove(id, x, y, writesocket)) + { + case 0: + { + player[id].specposx = x; + player[id].specposy = y; + break; + } + case 1: + { + break; + } + } + return paketlength; +} + +int chatmessage(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 4; + unsigned char team, unknown; + int paketsize; + + if (paketlength > length) + { + printf("Invalid packet (chatmessage)!\n"); + return length; + } + + int position = 0; + position++; + team = message[position]; + position++; + + paketsize = message[position]; + if (paketsize > 255 || paketsize >= (length - position + 1)) + { + printf("Message too big\n"); + return length; + } + position++; + paketlength += paketsize; + + unknown = message[position]; + position++; + + unsigned char *string = malloc(paketsize); + if (string == NULL) + error_exit("Memory error ( chatmessage() )\n"); + memcpy(string, message + position, paketsize); + + string[paketsize] = '\0'; + position += paketsize; + + if (paketsize >= 6){ + if (strncmp((char *)string, "!log", 4) == 0){ + char* log = malloc(sizeof(char)*(paketsize-4)); + if (log == NULL) error_exit("Memory error ( chatmessage() -> log )\n"); + strcpy(log,(char *)string+5); + //printf("[LOG]: %s\n",log); + eprintf("[LOG]: %s\n",log); + free(log); free(string); + return paketlength; + } + } + switch (OnChatMessage(id, string, team, writesocket)) + { + case 0: + break; + default: + printf("Unknown Return value for OnChatMessage()!\n"); + break; + } + + free(string); + + return paketlength; +} + +int joinroutine_known(unsigned char *message, int length, int id, + int writesocket) +{ + int paketlength = 2; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + switch (message[1]) + { + case 0: + { + paketlength = 2; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + break; + } + case 1: + { + if (player[id].joinstatus == 1) + { + paketlength = 16; // ??? + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + + int position = 2; + //Playername + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Playername too big\n"); + return length; + } + paketlength += stringsize; + position++; + + player[id].name = malloc(stringsize); + if (player[id].name == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].name, message + position, stringsize); + player[id].name[stringsize] = '\0'; + position += stringsize; //+1 because after it there is a null byte, so ignore it + + //printf("Player %s connected..\n", player[id].name); + + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Password too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *password = malloc(stringsize); + if (password == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(password, message + position, stringsize); + password[stringsize] = '\0'; + position += stringsize; + + //printf("\tPassword: "); + /* + int i; + for (i = 0; i <= u_strlen(password); i++) + { + printf("%d-", password[i]); + } + printf("\n"); + */ + + //Encryption String + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Encryption too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *encryption1 = malloc(stringsize); + if (encryption1 == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(encryption1, message + position, stringsize); + encryption1[stringsize] = '\0'; + position += stringsize; + + //printf("\tEncryptionstring: %s\n", encryption1); + + //Player Version + player[id].version = message[position]; + position++; + //printf("\tVersion: %d\n", player[id].version); + position++; //Null-byte + + + //USGN ID + player[id].usgn = malloc(sizeof(unsigned short)); + if (player[id].usgn == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].usgn, message + position, 2); //sizeof(unsigned short) == 2 + position += 4; //2 bytes + 2 null bytes + /* + #else + *player[id].usgn = endian_swap_short(player[id].usgn); + #endif + */ + //printf("\tUSGN-ID: %u\n", *player[id].usgn); + + + //Spraylogo + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Spraylogoname too big\n"); + return length; + }; + paketlength += stringsize; + position++; + + player[id].spraylogo = malloc(stringsize); + if (player[id].spraylogo == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].spraylogo, message + position, stringsize); + player[id].spraylogo[stringsize] = '\0'; + position += stringsize; + + //printf("\tSpraylogo: %s\n", player[id].spraylogo); + + + //Map-Hash + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Map-Hash too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *maphash = malloc(stringsize); + if (maphash == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(maphash, message + position, stringsize); + maphash[stringsize] = '\0'; + position += stringsize; + + //printf("\tMap-Hash: %s\n", maphash); + + position++; //Nullbyte + + //WIN + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("WIN too big\n"); + return length; + } + paketlength += stringsize; + position++; + + player[id].win = malloc(stringsize); + if (player[id].win == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].win, message + position, stringsize); + player[id].win[stringsize] = '\0'; + position += stringsize; + + //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); + + unsigned char *buffer = NULL; + stringsize = 0; + int tempstatus = CheckPlayerData(password); + switch (tempstatus) + { + case 0x00: + stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 2; + position++; + buffer[position] = 0; //Normal + position++; + buffer[position] = id; + position++; + buffer[position] = u_strlen(sv_map); + position++; + memcpy(buffer + position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); + buffer[position] = u_strlen(pre_authcode); + position++; + memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); + position += u_strlen(pre_authcode); + player[id].joinstatus = 2; + break; + + default: + { + stringsize = 3; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 2; + position++; + buffer[position] = tempstatus; //Everyone is banned (just for testing) + position++; + player[id].joinstatus = 0; + break; + } + + } + //stringsize = 16 + u_strlen(sv_map); + + /* + 0 - Normal + 1 - Password wrong + 2 - USGN only + 3 - Server full + 4 - Banned + 5 - Another Game Version + 6 - ?? + 7 - Can't validate user (USGN offline) + 8 - ?? + 9 - Connection already exists + 10 - Wrong client (pre_authcode) + 11 - Diffrent map (temp, etc.) + 12 - Map unknown (maptransfer disabled) + 13++ - Failed to join + */ + + if (stringsize != 0) + SendToPlayer(buffer, stringsize, id, 1, writesocket); + + free(encryption1); + free(maphash); + free(buffer); + + onlineplayer++; + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + case 3: + { + if (player[id].joinstatus == 2) + { + int position = 2; + + paketlength = 5; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + + //Map-Hash + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Map-Hash too big\n"); + return length; + } + position++; + + unsigned char *maphash = malloc(stringsize); + if (maphash == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(maphash, message + position, stringsize); + maphash[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tMaphash: %s\n", maphash); + + //pre_authcode_respond + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("pre_authcon_respond too big\n"); + return length; + } + position++; + + unsigned char *pre_authcode_respond = malloc(stringsize); + if (pre_authcode_respond == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(pre_authcode_respond, message + position, stringsize); + pre_authcode_respond[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); + + //Player Version + //unsigned char mapstatus = message[position]; //avoid warning + position++; + //printf("\tMapstatus: %d\n", mapstatus); + + free(pre_authcode_respond); + free(maphash); + + //Respond + stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 4; + position++; + buffer[position] = 0; //CheckPlayerData() + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + player[id].joinstatus = 3; + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + case 5: + { + if (player[id].joinstatus == 3) + { + int position = 2; + + paketlength = 3; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + //Map-Hash + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Mapname too big\n"); + return length; + } + position++; + + unsigned char *mapname = malloc(stringsize); + if (mapname == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(mapname, message + position, stringsize); + mapname[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tMapname: %s\n", mapname); + + + //----------- ServerData ----------- + + stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 6; + position++; + buffer[position] = 0; //CheckPlayerData() + position++; + + buffer[position] = u_strlen(sv_map); + position++; + memcpy(buffer + position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); + + buffer[position] = u_strlen(sv_name); + position++; + memcpy(buffer + position, sv_name, u_strlen(sv_name)); + position += u_strlen(sv_name); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = sv_friendlyfire; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = mp_roundtime; + position++; + buffer[position] = mp_freezetime; + position++; + buffer[position] = mp_c4timer; + position++; + buffer[position] = 32; //Unknown + position++; + buffer[position] = 124; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 1; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = sv_maxplayers; + position++; + buffer[position] = sv_fow; + position++; + buffer[position] = mp_specmode; + position++; + buffer[position] = sv_gamemode; + position++; + buffer[position] = mp_respawndelay; + position++; + buffer[position] = mp_infammo; + position++; + buffer[position] = 3; //u_strlen ACK + position++; + buffer[position] = 65; //A + position++; + buffer[position] = 67; //C + position++; + buffer[position] = 75; //K + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- PlayerData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 1; + position++; + buffer[position] = onlineplayer; + position++; + + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 1 && i != id) + { + unsigned char *encodedname; + encodedname = GetEncodedString(player[i].name, u_strlen( + player[i].name)); + unsigned short *deaths = &player[i].deaths; + unsigned short tempscore = (unsigned) (player[i].deaths + + 1000); + unsigned short *score = &tempscore; + + unsigned short tempx = (player[i].x); + unsigned short tempy = (player[i].y); + unsigned short *x = &tempx; + unsigned short *y = &tempy; + + float *ptemprotation = &player[i].rotation; + + int playersize = 25 + u_strlen(encodedname); + buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + buffer[position] = i; + position++; + + buffer[position] = u_strlen(encodedname); + position++; + memcpy(buffer + position, encodedname, + u_strlen(encodedname)); + position += u_strlen(encodedname); + free(encodedname); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = player[i].team; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + /* + buffer[position] = score[0]; //Deaths + position++; + buffer[position] = score[1]; //Deaths + position++; + */ + memcpy(buffer + position, score, 2); + position += 2; + /* + buffer[position] = deaths[0]; //Deaths + position++; + buffer[position] = deaths[1]; //Deaths + position++; + */ + memcpy(buffer + position, deaths, 2); + position += 2; + memcpy(buffer + position, x, 2); + position += 2; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + memcpy(buffer + position, y, 2); + position += 2; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = ptemprotation[0]; //Rotation + position++; + buffer[position] = ptemprotation[1]; //Rotation + position++; + buffer[position] = player[i].health; //Health + position++; + buffer[position] = player[i].armor; //Armor + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] + = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe + position++; + buffer[position] = 0; //Unknown + position++; + /* + 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 + 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 + 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 + 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 + e8 03 00 00 12 01 00 00 01 03 + e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 + e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 + 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 + */ + } + } + if (1) + { + unsigned char *encodedname; + encodedname = GetEncodedString(player[id].name, u_strlen( + player[id].name)); + + int playersize = 25 + u_strlen(encodedname); + buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + buffer[position] = id; + position++; + + buffer[position] = u_strlen(encodedname); + position++; + memcpy(buffer + position, encodedname, u_strlen(encodedname)); + position += u_strlen(encodedname); + free(encodedname); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = player[id].team; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 232; //Unknown + position++; + buffer[position] = 3; //Unknown + position++; + buffer[position] = 0; //Deaths + position++; + buffer[position] = 0; //Deaths + position++; + buffer[position] = 0; //X + position++; + buffer[position] = 0; //X + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Y + position++; + buffer[position] = 0; //Y + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Health + position++; + buffer[position] = 0; //Armor + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Aktuelle Waffe 50 = Knife + position++; + buffer[position] = 0; //Unknown + position++; + } + + SendToPlayer(buffer, position, id, 1, writesocket); + free(buffer); + + //----------- PlayerData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 1; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- HostageData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 2; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- ItemData ----------- + + /* + fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 + */ + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 3; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- EnityData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 4; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- DynamicObjectData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 5; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- ProjectileData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 6; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- DynamicObjectImageData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 7; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- Final ACK ----------- + stringsize = 7; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 200; //third payload + position++; + buffer[position] = 3; //u_strlen ACK + position++; + buffer[position] = 65; //A + position++; + buffer[position] = 67; //C + position++; + buffer[position] = 75; //K + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + player[id].joinstatus = 4; + free(mapname); + + OnJoin(id, writesocket); + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + default: + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + + return paketlength; +} + +int leave(int id, int writesocket) +{ + OnLeave(id, writesocket); + + free(player[id].name); + free(player[id].usgn); + free(player[id].spraylogo); + free(player[id].win); + + player[id].name = NULL; + player[id].usgn = NULL; + player[id].spraylogo = NULL; + player[id].win = NULL; + + onlineplayer--; + + ClearPlayer(id); + + return 2; +} + +int reload(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 2; + if (length < paketlength) + { + printf("Invalid packet (buy)!\n"); + return length; + } + + int position = 1; + int status; + + status = message[position]; + position++; + + if (status == 1) + { + SendReloadMessage(id, 1, writesocket); + player[id].reloading = player[id].actualweapon; + player[id].reloadtimer + = mtime() + + weapons[player[id].slot[player[id].actualweapon].id].reloadtime; + } + return paketlength; +} + +int spray(unsigned char *message, int length, int id, int writesocket) +{ + // 28 0 xx yy c + // 0 1 23 45 6 + struct{ + unsigned char hi; unsigned char lo; + } x, y; + + if (length < 7) + { + printf("Invalid packet (spray)!\n"); + return length; + } + + x.lo = message[2]; + x.hi = message[3]; + + y.lo = message[4]; + y.hi = message[5]; + + unsigned short xx = x.hi*256+x.lo, yy = y.hi*256+y.lo; + unsigned char c = message[6]; + unsigned char i = (char)id; + + // Postprocessing if needed, then send back exact same data + // xx and yy are positions, not tiles. + + SendSprayMessage(i, xx, yy, c, writesocket); + return 7; +} diff --git a/src/respond_messages.c b/src/respond_messages.c index af65bbc..7d66a92 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,624 +1,694 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/respond_messages.h" - -void SendSpawnMessage(int id, unsigned short x, unsigned short y, - int writesocket) -{ - int stringsize = 11; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendSpawnMessage() )\n"); - - int position = 0; - - unsigned short *spawnx = &x; - unsigned short *spawny = &y; - unsigned short *pmoney = &player[id].money; - - buffer[position] = 21; - position++; - buffer[position] = id; - position++; - memcpy(buffer + position, spawnx, 2); - position += 2; - memcpy(buffer + position, spawny, 2); - position += 2; - buffer[position] = 50; //Team - position++; - buffer[position] = 0; - position++; - /* - buffer[position] = pmoney[1]; //Money - position++; - buffer[position] = pmoney[0]; // Money - position++; - */ - memcpy(buffer + position, pmoney, 2); - position += 2; - - int i, count; - count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); - buffer[position] = count; - position++; - - buffer = realloc(buffer, stringsize + count); - if (buffer == NULL) - error_exit("Memory error ( SendSpawnMessage() )\n"); - - for (i = 0; i <= count - 1; i++) - { - buffer[position] = startweapons[i]; - position++; - - GivePlayerWeapon(id, startweapons[i]); - if (startweapons[i] == 50) - player[id].actualweapon = i; //else 0 - } - - /* - int count, i; - count = 0; - for(i = 0; i <= 10; i++) - { - if(player[id].slot[i].id != 0) - { - count++; - } - } - buffer[position] = count; //Count - position++; - - buffer = realloc(buffer, stringsize + count); - if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); - - for(i = 0; i <= 10; i++) - { - if(player[id].slot[i].id != 0) - { - buffer[position] = player[id].slot[i].id; - position++; - } - } - */ - - SendToAll(buffer, stringsize + count, 1, writesocket); - - free(buffer); -} - -void SendAdvancedFireMessage(int id, int status, int writesocket) -{ - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendFireMessage() )\n"); - - int position = 0; - - buffer[position] = 8; - position++; - buffer[position] = id; - position++; - buffer[position] = status; - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - - free(buffer); -} - -void SendFireMessage(int id, int writesocket) -{ - int stringsize = 2; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendFireMessage() )\n"); - - int position = 0; - - buffer[position] = 7; - position++; - buffer[position] = id; - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - - free(buffer); -} - -void SendBuyMessage(int id, int wpnid, int writesocket) -{ - int stringsize = 6; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendBuyMessage() )\n"); - - int position = 0; - - buffer[position] = 23; - position++; - buffer[position] = id; - position++; - buffer[position] = wpnid; - position++; - memcpy(buffer + position, &player[id].money, 2); - position += 2; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - - free(buffer); - - SendWeaponChangeMessage(id, wpnid, writesocket); -} - -void SendHitMessage(int id, int victim, int health, int writesocket) -{ - int stringsize = 5; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendHitMessage() )\n"); - - int position = 0; - - buffer[position] = 17; - position++; - buffer[position] = id; - position++; - buffer[position] = victim; - position++; - buffer[position] = health; - position++; - buffer[position] = 0; - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - - free(buffer); -} - -void SendWeaponChangeMessage(int id, int wpnid, int writesocket) -{ - int stringsize = 4; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendWeaponChangeMessage() )\n"); - - int position = 0; - - buffer[position] = 9; - position++; - buffer[position] = id; - position++; - buffer[position] = wpnid; - position++; - buffer[position] = 0; - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - - free(buffer); -} - -void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, - int writesocket) -{ - int stringsize = 6; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendSpawnMessage() )\n"); - - int position = 0; - - unsigned short *px = &x; - unsigned short *py = &y; - - if (status == 0) - buffer[position] = 11; - else if (status == 1) - buffer[position] = 10; - - position++; - buffer[position] = id; - position++; - memcpy(buffer + position, px, 2); - position += 2; - memcpy(buffer + position, py, 2); - position += 2; - - SendToAllOther(id, buffer, stringsize, 1, writesocket); - - free(buffer); -} - -void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, - float rotation, int writesocket) -{ - int stringsize = 10; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendPosRotUpdate() )\n"); - - int position = 0; - - unsigned short *px = &x; - unsigned short *py = &y; - //if(rotation > 180) rotation = (rotation - 360); - //unsigned short *protation = &rotation; //2 Bytes cut off - - if (status == 0) - buffer[position] = 14; - else if (status == 1) - buffer[position] = 13; - - position++; - buffer[position] = id; - position++; - memcpy(buffer + position, px, 2); - position += 2; - memcpy(buffer + position, py, 2); - position += 2; - memcpy(buffer + position, &rotation, 4); - position += 4; - - SendToAllOther(id, buffer, stringsize, 1, writesocket); - - free(buffer); -} - -void SendRotUpdate(int id, float rotation, int writesocket) -{ - int stringsize = 6; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendRotUpdate() )\n"); - - int position = 0; - //if(rotation > 180) rotation = (rotation - 360); - - - buffer[position] = 12; - position++; - buffer[position] = id; - position++; - memcpy(buffer + position, &rotation, sizeof(float)); - - SendToAllOther(id, buffer, stringsize, 1, writesocket); - - free(buffer); -} - -void SendMessageToPlayer(int id, char *message, int status, int writesocket) -{ - /* - 1 - Chat - 2 - Screen - 3 - Console - 4 - Crash - */ - int stringsize = 5 + strlen(message); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendChatMessage() )\n"); - - int position = 0; - - buffer[position] = 240; - position++; - buffer[position] = 0; - position++; - buffer[position] = status; - position++; - buffer[position] = strlen(message); - position++; - buffer[position] = 0; - position++; - memcpy(buffer + position, message, strlen(message)); - position += strlen(message); - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - - switch (status) - { - case 1: - printf("To %s (Chat): %s\n", player[id].name ,message); - break; - case 2: - printf("To %s (Screen): %s\n", player[id].name ,message); - break; - case 3: - printf("To %s (Console): %s\n", player[id].name ,message); - break; - default: - printf("Unknown status (SendMessageToPlayer())!\n"); - break; - } - - free(buffer); -} - -void SendMessageToAll(char *message, int status, int writesocket) -{ - /* - 1 - Chat - 2 - Screen - 3 - Console - 4 - Crash - */ - int stringsize = 5 + strlen(message); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendChatMessage() )\n"); - - int position = 0; - - buffer[position] = 240; - position++; - buffer[position] = 0; - position++; - buffer[position] = status; - position++; - buffer[position] = strlen(message); - position++; - buffer[position] = 0; - position++; - memcpy(buffer + position, message, strlen(message)); - position += strlen(message); - - SendToAll(buffer, stringsize, 1, writesocket); - - switch (status) - { - case 1: - printf("To All (Chat): %s\n", message); - break; - case 2: - printf("To All (Screen): %s\n", message); - break; - case 3: - printf("To All (Console): %s\n", message); - break; - default: - printf("Unknown status (SendMessageToAll())!\n"); - break; - } - - free(buffer); -} - -void SendJoinMessage(int id, int writesocket) -{ - int stringsize = 4 + u_strlen(player[id].name); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendJoinMessage() )\n"); - - int position = 0; - - buffer[position] = 248; - position++; - buffer[position] = id; - position++; - buffer[position] = u_strlen(player[id].name); - position++; - - memcpy(buffer + position, player[id].name, u_strlen(player[id].name)); - position += u_strlen(player[id].name); - - buffer[position] = 0; //u_strlen ACK - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); -} - -void SendLeaveMessage(int id, int writesocket) -{ - if (player[id].joinstatus >= 4) - { - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendLeaveMessage() )\n"); - int position = 0; - - buffer[position] = 253; - position++; - buffer[position] = id; - position++; - buffer[position] = 0; //u_strlen ACK - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); - } -} - -void SendChatMessage(int id, unsigned char *message, int team, int writesocket) -{ - int stringsize = 5 + u_strlen(message); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendChatMessage() )\n"); - - int position = 0; - - buffer[position] = 240; - position++; - buffer[position] = id; - position++; - buffer[position] = team; - position++; - buffer[position] = u_strlen(message); - position++; - buffer[position] = 0; - position++; - memcpy(buffer + position, message, u_strlen(message)); - position += u_strlen(message); - if (team == 1) - { - SendToAll(buffer, stringsize, 1, writesocket); - } - else if (team == 2) - { - SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); - } - free(buffer); -} - -void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, - int writesocket) -{ - int stringsize = 4; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendJoinMessage() )\n"); - - int position = 0; - - buffer[position] = 20; - position++; - buffer[position] = id; - position++; - buffer[position] = team; - position++; - buffer[position] = skin; - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); -} - -void PingAllPlayer(int writesocket, time_t *firsttime) -{ - time_t actualtime; - time(&actualtime); - if (actualtime >= (*firsttime + 5)) - { - *firsttime = actualtime; - SendPingList(writesocket); - - SendMessageToAll("This is an alpha version! Don't play at it!", 1, - writesocket); //Do not remove or change this until server reaches beta status - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && player[i].joinstatus >= 4) - { - int stringsize = 5; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendJoinMessage() )\n"); - - int position = 0; - - buffer[position] = 249; - position++; - buffer[position] = 0; - position++; - buffer[position] = 32; - position++; - buffer[position] = 191; - position++; - buffer[position] = 0; - position++; - - player[i].start = mtime(); - - SendToPlayer(buffer, stringsize, i, 0, writesocket); - - free(buffer); - } - - } - } -} - -void SendReloadMessage(int id, int status, int writesocket) -{ - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendReloadMessage() )\n"); - - int position = 0; - - buffer[position] = 16; - position++; - buffer[position] = id; - position++; - buffer[position] = status; - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); -} -//FIXME complete SendKillMessage -void SendKillMessage(int id, int writesocket) -{ - - /* - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); - - int position = 0; - - buffer[position] = 16; - position++; - buffer[position] = hitter; - position++; - buffer[position] = victim; - position++; - buffer[position] = wpnid; - position++; - - - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); - */ -} - -void SendPingList(int writesocket) -{ - int count = onlineplayer; - int stringsize = 2 + count * 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) - error_exit("Memory error ( SendPingList() )\n"); - - int position = 0; - - buffer[position] = 247; - position++; - buffer[position] = count; - position++; - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && player[i].joinstatus >= 4) - { - buffer[position] = i; - position++; - memcpy(buffer + position, &player[i].latency, 2); - position += 2; - /* - buffer[position] = player[i].latency; - position++; - buffer[position] = 0; - position++; - */ - } - } - - SendToAll(buffer, stringsize, 0, writesocket); - free(buffer); -} +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/respond_messages.h" + +void SendSpawnMessage(int id, unsigned short x, unsigned short y, + int writesocket) +{ + int stringsize = 11; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendSpawnMessage() )\n"); + + int position = 0; + + unsigned short *spawnx = &x; + unsigned short *spawny = &y; + unsigned short *pmoney = &player[id].money; + + buffer[position] = 21; + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, spawnx, 2); + position += 2; + memcpy(buffer + position, spawny, 2); + position += 2; + buffer[position] = 50; //Team + position++; + buffer[position] = 0; + position++; + /* + buffer[position] = pmoney[1]; //Money + position++; + buffer[position] = pmoney[0]; // Money + position++; + */ + memcpy(buffer + position, pmoney, 2); + position += 2; + + int i, count; + count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); + buffer[position] = count; + position++; + + buffer = realloc(buffer, stringsize + count); + if (buffer == NULL) + error_exit("Memory error ( SendSpawnMessage() )\n"); + + for (i = 0; i <= count - 1; i++) + { + buffer[position] = startweapons[i]; + position++; + + GivePlayerWeapon(id, startweapons[i]); + if (startweapons[i] == 50) + player[id].actualweapon = i; //else 0 + } + + /* + int count, i; + count = 0; + for(i = 0; i <= 10; i++) + { + if(player[id].slot[i].id != 0) + { + count++; + } + } + buffer[position] = count; //Count + position++; + + buffer = realloc(buffer, stringsize + count); + if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); + + for(i = 0; i <= 10; i++) + { + if(player[id].slot[i].id != 0) + { + buffer[position] = player[id].slot[i].id; + position++; + } + } + */ + + SendToAll(buffer, stringsize + count, 1, writesocket); + + free(buffer); +} + +void SendAdvancedFireMessage(int id, int status, int writesocket) +{ + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendFireMessage() )\n"); + + int position = 0; + + buffer[position] = 8; + position++; + buffer[position] = id; + position++; + buffer[position] = status; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendFireMessage(int id, int writesocket) +{ + int stringsize = 2; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendFireMessage() )\n"); + + int position = 0; + + buffer[position] = 7; + position++; + buffer[position] = id; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendBuyMessage(int id, int wpnid, int writesocket) +{ + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendBuyMessage() )\n"); + + int position = 0; + + buffer[position] = 23; + position++; + buffer[position] = id; + position++; + buffer[position] = wpnid; + position++; + memcpy(buffer + position, &player[id].money, 2); + position += 2; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + + free(buffer); + + SendWeaponChangeMessage(id, wpnid, writesocket); +} + +void SendHitMessage(int id, int victim, int health, int writesocket) +{ + int stringsize = 5; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendHitMessage() )\n"); + + int position = 0; + + buffer[position] = 17; + position++; + buffer[position] = id; + position++; + buffer[position] = victim; + position++; + buffer[position] = health; + position++; + buffer[position] = 0; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendWeaponChangeMessage(int id, int wpnid, int writesocket) +{ + int stringsize = 4; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendWeaponChangeMessage() )\n"); + + int position = 0; + + buffer[position] = 9; + position++; + buffer[position] = id; + position++; + buffer[position] = wpnid; + position++; + buffer[position] = 0; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, + int writesocket) +{ + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendSpawnMessage() )\n"); + + int position = 0; + + unsigned short *px = &x; + unsigned short *py = &y; + + if (status == 0) + buffer[position] = 11; + else if (status == 1) + buffer[position] = 10; + + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, px, 2); + position += 2; + memcpy(buffer + position, py, 2); + position += 2; + + SendToAllOther(id, buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, + float rotation, int writesocket) +{ + int stringsize = 10; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendPosRotUpdate() )\n"); + + int position = 0; + + unsigned short *px = &x; + unsigned short *py = &y; + //if(rotation > 180) rotation = (rotation - 360); + //unsigned short *protation = &rotation; //2 Bytes cut off + + if (status == 0) + buffer[position] = 14; + else if (status == 1) + buffer[position] = 13; + + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, px, 2); + position += 2; + memcpy(buffer + position, py, 2); + position += 2; + memcpy(buffer + position, &rotation, 4); + position += 4; + + SendToAllOther(id, buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendRotUpdate(int id, float rotation, int writesocket) +{ + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendRotUpdate() )\n"); + + int position = 0; + //if(rotation > 180) rotation = (rotation - 360); + + + buffer[position] = 12; + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, &rotation, sizeof(float)); + + SendToAllOther(id, buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendMessageToPlayer(int id, char *message, int status, int writesocket) +{ + /* + 1 - Chat + 2 - Screen + 3 - Console + 4 - Crash + */ + int stringsize = 5 + strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = 0; + position++; + buffer[position] = status; + position++; + buffer[position] = strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer + position, message, strlen(message)); + position += strlen(message); + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + + switch (status) + { + case 1: + printf("To %s (Chat): %s\n", player[id].name ,message); + break; + case 2: + printf("To %s (Screen): %s\n", player[id].name ,message); + break; + case 3: + printf("To %s (Console): %s\n", player[id].name ,message); + break; + default: + printf("Unknown status (SendMessageToPlayer())!\n"); + break; + } + + free(buffer); +} + +void SendMessageToAll(char *message, int status, int writesocket) +{ + /* + 1 - Chat + 2 - Screen + 3 - Console + 4 - Crash + */ + int stringsize = 5 + strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = 0; + position++; + buffer[position] = status; + position++; + buffer[position] = strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer + position, message, strlen(message)); + position += strlen(message); + + SendToAll(buffer, stringsize, 1, writesocket); + + switch (status) + { + case 1: + printf("To All (Chat): %s\n", message); + break; + case 2: + printf("To All (Screen): %s\n", message); + break; + case 3: + printf("To All (Console): %s\n", message); + break; + default: + printf("Unknown status (SendMessageToAll())!\n"); + break; + } + + free(buffer); +} + +void SendJoinMessage(int id, int writesocket) +{ + int stringsize = 4 + u_strlen(player[id].name); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 248; + position++; + buffer[position] = id; + position++; + buffer[position] = u_strlen(player[id].name); + position++; + + memcpy(buffer + position, player[id].name, u_strlen(player[id].name)); + position += u_strlen(player[id].name); + + buffer[position] = 0; //u_strlen ACK + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); +} + +void SendLeaveMessage(int id, int writesocket) +{ + if (player[id].joinstatus >= 4) + { + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendLeaveMessage() )\n"); + int position = 0; + + buffer[position] = 253; + position++; + buffer[position] = id; + position++; + buffer[position] = 0; //u_strlen ACK + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); + } +} + +void SendChatMessage(int id, unsigned char *message, int team, int writesocket) +{ + int stringsize = 5 + u_strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = id; + position++; + buffer[position] = team; + position++; + buffer[position] = u_strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer + position, message, u_strlen(message)); + position += u_strlen(message); + if (team == 1) + { + SendToAll(buffer, stringsize, 1, writesocket); + } + else if (team == 2) + { + SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); + } + free(buffer); +} + +void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, + int writesocket) +{ + int stringsize = 4; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 20; + position++; + buffer[position] = id; + position++; + buffer[position] = team; + position++; + buffer[position] = skin; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); +} + +void PingAllPlayer(int writesocket, time_t *firsttime) +{ + time_t actualtime; + time(&actualtime); + if (actualtime >= (*firsttime + 5)) + { + *firsttime = actualtime; + SendPingList(writesocket); + + SendMessageToAll("This is an alpha version! Don't play at it!", 1, + writesocket); //Do not remove or change this until server reaches beta status + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4) + { + int stringsize = 5; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 249; + position++; + buffer[position] = 0; + position++; + buffer[position] = 32; + position++; + buffer[position] = 191; + position++; + buffer[position] = 0; + position++; + + player[i].start = mtime(); + + SendToPlayer(buffer, stringsize, i, 0, writesocket); + + free(buffer); + } + + } + } +} + +void SendReloadMessage(int id, int status, int writesocket) +{ + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendReloadMessage() )\n"); + + int position = 0; + + buffer[position] = 16; + position++; + buffer[position] = id; + position++; + buffer[position] = status; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); +} + +// 28 - id - xx - yy - c +void SendSprayMessage(char id, unsigned short xx, unsigned short yy, char c, + int writesocket) +{ + int stringsize = 8; + unsigned char *buffer = malloc(stringsize * sizeof(char)); + if (buffer == NULL) + error_exit("Memory error ( SendReloadMessage() )\n"); + + int position = 0; + + buffer[position++] = 28; + buffer[position++] = 0; + buffer[position++] = id; + memcpy(buffer + position, &xx, 2); + position += 2; + memcpy(buffer + position, &yy, 2); + position += 2; + buffer[position++] = c; + + // SendToAll(buffer, stringsize, 1, writesocket); -- Make sure that the spray-image send packet is crafted first. + free(buffer); +} + +//FIXME complete SendKillMessage +void SendKillMessage(int id, int writesocket) +{ + + /* + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); + + int position = 0; + + buffer[position] = 16; + position++; + buffer[position] = hitter; + position++; + buffer[position] = victim; + position++; + buffer[position] = wpnid; + position++; + + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); + */ +} + +void SendPingList(int writesocket) +{ + int count = onlineplayer; + int stringsize = 2 + count * 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendPingList() )\n"); + + int position = 0; + + buffer[position] = 247; + position++; + buffer[position] = count; + position++; + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4) + { + buffer[position] = i; + position++; + memcpy(buffer + position, &player[i].latency, 2); + position += 2; + /* + buffer[position] = player[i].latency; + position++; + buffer[position] = 0; + position++; + */ + } + } + + SendToAll(buffer, stringsize, 0, writesocket); + free(buffer); +} + +void SendBuyFailedMessage(int id, int status, int writesocket) +{ + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendBuyFailedMessage() )\n"); + + int position = 0; + buffer[position] = 23; + position++; + buffer[position] = 1; + position++; + buffer[position] = status; + position++; + buffer[position] = 44; + position++; + buffer[position] = 1; + position++; + buffer[position] = 0; + position++; + //TODO what does the last lines mean? + + /* + * 242 nothing + * 243 Grenade rebuying is not allowed at this server + * 244 it's not allowed to buy that weapon at this server + * 245 you can't carry more of this + * 246 you can't carry more of this + * 247 you can't carry an additional weapon + * 248 you can't buy more ammo + * 249 you are not allowed to buy anything + * 250 buying is not allowed + * 251 you have already this or something better + * 252 you can't buy this item; + * 253 insufficient fund; + * 254 buytime passed; + * 255 you are not in a buyzone + * +*/ + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + + free(buffer); +} diff --git a/src/script-functions.c b/src/script-functions.c index f238c7d..51956bc 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,492 +1,525 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/script-functions.h" - -/* - int OnJoin(int id, int writesocket) - id - Who joins - Return Values: - 0 - OK - */ -int OnJoin(int id, int writesocket) -{ - SendJoinMessage(id, writesocket); - printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); - return 0; -} - -/* - int OnLeave(int id, int writesocket) - id - Who leaves - Return Values: - 0 - OK - */ -int OnLeave(int id, int writesocket) -{ - SendLeaveMessage(id, writesocket); - printf("%s has left the game!\n", player[id].name); - return 0; -} - -/* - int OnSpecmove(int id, int newx, int newy, int writesocket) - Return Values: - 0 - OK - 1 - Don't save it - */ - -int OnSpecmove(int id, int newx, int newy, int writesocket) -{ - return 0; -} - -/* - int OnServerstart() - Return Values: - 0 - OK - */ -int OnServerStart() -{ - time_t rawtime; - time(&rawtime); - printf("********** Server started **********\n"); - printf("%s", ctime(&rawtime)); - return 0; -} - -/* - int OnExit() - Return Values: - 0 - OK - */ -int OnExit() -{ - printf("********** Server Shutdown! **********\n\n\n\n\n"); - return 0; -} - -/* - int OnRespawnRequest(int id, int writesocket) - Return Values: - 0 - Respawn - 1 - Don't Respawn - */ -int OnRespawnRequest(int id, int writesocket) -{ - if (player[id].dead == 1) - return 0; - else - return 1; -} - -/* - int OnRespawn(int id, int writesocket) - Return Values: - 0 - OK - */ -int OnRespawn(int id, int writesocket) -{ - return 0; -} - -/* - int OnRespawn(int id, int writesocket) - Return Values: - 0 - OK - */ -int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) -{ - int i; - for (i = 0; i <= 9; i++) - { - if (player[id].slot[i].id == wpnid) - { - player[id].actualweapon = i; - if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) - { - player[id].zoommode = 0; - } - player[id].reloading = 0; - - printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); - return 0; - } - } - return 1; -} - -/* - int OnAdvancedFire(int id, int status, int writesocket) - Return Values: - 0 - OK - 1 - Not OK - */ -int OnAdvancedFire(int id, int status, int writesocket) -{ - int wpnid = player[id].slot[player[id].actualweapon].id; - - int temptime = mtime(); - if (temptime < player[id].zoomtimer) - { - printf("Zoomtimer error!\n"); - return 1; - } - else - { - player[id].zoomtimer = mtime() + 500; - } - - switch (weapons[wpnid].special) - { - case 0: - printf("%s tried to hack!\n", player[id].name); - return 1; - case 1: - case 2: - { - if (status <= 1) - { - player[id].zoommode = status; - break; - } - return 1; - } - case 3: - { - player[id].zoommode = 1; - OnFire(id, writesocket); - player[id].zoommode = 0; - break; - } - case 4: - { - if (status <= 1) - { - player[id].zoommode = status; - break; - } - return 1; - } - case 5: - { - if (status <= 2 && player[id].zoommode + 1 == status) - { - player[id].zoommode = status; - break; - } - else if (player[id].zoommode == 2) - { - player[id].zoommode = 0; - break; - } - return 1; - } - default: - { - SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); - return 1; - } - - } - - return 0; -} -/* - int OnFire(int id, int writesocket) - Return Values: - 0 - OK - 1 - Not OK - */ -int OnFire(int id, int writesocket) -{ - //printf("%s tried to shoot!\n", player[id].name); - short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; - if (*ammo1 <= 0 && *ammo1 != -1) - { - printf("Not enough ammo!\n"); - return 1; - } - else - { - if (*ammo1 != -1) - { - *ammo1 = *ammo1 - 1; - } - } - int temptime = mtime(); - if (temptime < player[id].firetimer) - { - printf("Firetimer error!\n"); - return 1; - } - else - { - player[id].firetimer = mtime() - + weapons[player[id].slot[player[id].actualweapon].id].freq; - } - - int i; - int range = weapons[player[id].slot[player[id].actualweapon].id].range; - - int startx = player[id].x; - int starty = player[id].y; - float rotx; - float roty; - float temprot = player[id].rotation; - - short playershit[MAX_CLIENTS] = - { 0 }; - - if (temprot < 0) - { - temprot = 360 - (temprot * -1); - } - temprot = 360 - temprot; - - temprot += 90; - if (temprot > 360) - { - temprot = temprot - 360; - } - - rotx = cos((temprot) * PI / 180); - roty = sin((temprot) * PI / 180); - - for (i = 1; i <= range; i++) - { - startx += i * rotx; - starty -= i * roty; - - int tilex = (int) (startx) / 32; - int tiley = (int) (starty) / 32; - - if (tilex <= 0 || tiley <= 0) - break; - int tilemode = map[tilex][tiley].mode; - if (tilemode == 1 || tilemode == 3 || tilemode == 4) - { - break; - } - - int b; - for (b = 1; b <= sv_maxplayers; b++) - { - if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id - && player[b].dead == 0 && playershit[b] == 0 - && player[id].team != player[b].team) - { - if (sqrt((player[b].x - startx) * (player[b].x - startx) - + (player[b].y - starty) * (player[b].y - starty)) - <= 16) - { - OnHit(id, b, writesocket); - playershit[b] = 1; - } - } - } - } - return 0; -} -/* - int OnHit(int hitter, int victim, int writesocket) - Return Values: - 0 - OK - */ -int OnHit(int hitter, int victim, int writesocket) -{ - int wpnid = player[hitter].slot[player[hitter].actualweapon].id; - int damage; - switch (player[hitter].zoommode) - { - case 0: - damage = weapons[wpnid].weapondamage; - break; - case 1: - damage = weapons[wpnid].weapondamage_z1; - break; - case 2: - damage = weapons[wpnid].weapondamage_z2; - break; - default: - damage = weapons[wpnid].weapondamage; - break; - } - if (player[victim].health - damage > 0) - { - player[victim].health -= damage; - SendHitMessage(victim, hitter, player[victim].health, writesocket); - printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); - } - else - { - OnKill(hitter, victim, wpnid, writesocket); - } - - return 0; -} - -int OnBuyAttempt(int id, int wpnid, int writesocket) -{ - if (player[id].money - weapons[wpnid].price >= 0) - { - int i; - for (i = 0; i <= 99; i++) - { - if (weapons[wpnid].name != NULL) //test if weapon available - { - if (weapons[wpnid].team == 0 || weapons[wpnid].team - == player[id].team) //Check if he is in the right team to buy this weapon - { - if (player[id].team == 1) - { - //Check if in buyzone - int b; - for (b = 0; b <= tspawncount; b++) - { - int playerx = player[id].x; - int playery = player[id].y; - int tempx = tspawnx[b] * 32; - int tempy = tspawny[b] * 32; - //If player in buyzone (5*5) - if (playerx >= tempx - 64 && playerx <= tempx + 64 - && playery >= tempy - 64 && playery - <= tempy + 64) - { - return 0; - } - } - } - else if (player[id].team == 2) - { - int b; - for (b = 0; b <= ctspawncount; b++) - { - int playerx = player[id].x; - int playery = player[id].y; - int tempx = ctspawnx[b] * 32; - int tempy = ctspawny[b] * 32; - //If player in buyzone (5*5) - if (playerx >= tempx - 64 && playerx <= tempx + 64 - && playery >= tempy - 64 && playery - <= tempy + 64) - { - return 0; - } - } - } - } - } - } - } - return 1; -} - -int OnBuy(int id, int wpnid, int writesocket) -{ - player[id].money -= weapons[wpnid].price; - player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot - printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); - return 0; -} - -int OnKill(int hitter, int victim, int wpnid, int writesocket) -{ - player[victim].health = 0; - player[victim].dead = 1; - player[hitter].score++; - player[hitter].kills++; - player[victim].deaths++; - RemoveAllPlayerWeapon(victim); - SendHitMessage(victim, hitter, player[victim].health, writesocket); - printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); - return 0; -} -/* - int OnChatMessage(int id, unsigned char *message, int team, int writesocket) - Return Values: - 0 - OK - */ -int OnChatMessage(int id, unsigned char *message, int team, int writesocket) -{ - if (team == 1) - { - printf("%s: %s\n", player[id].name, message); - } - else if (team == 2) - { - printf("%s (Team): %s\n", player[id].name, message); - } - SendChatMessage(id, message, team, writesocket); - return 0; -} - -/* - int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) - Return Values: - 0 - OK - 1 - Don't join - */ -int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, - int writesocket) -{ - return 0; -} - -/* - int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) - Return Values: - 0 - OK - */ -int OnTeamChange(int id, unsigned char team, unsigned char skin, - int writesocket) -{ - if (skin != 5) - { - switch (team) - { - case 0: - printf("%s is now spectator\n", player[id].name); - break; - case 1: - printf("%s is now terrorist\n", player[id].name); - break; - case 2: - printf("%s is now counter-terrorist\n", player[id].name); - break; - default: - printf("%s joined a unknown team\n", player[id].name); - break; - } - SendHitMessage(id, id, 0, writesocket); - player[id].dead = 1; - RemoveAllPlayerWeapon(id); - } - if (team <= 2) - { - SendTeamChangeMessage(id, team, skin, writesocket); - } - return 0; -} - -/* - int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) - Return Values: - 0 - OK - 1 - Don't move - */ -int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, - int writesocket) -{ - /* - int newx = (int)ceil((x)/32); - int newy = (int)ceil((y)/32); - printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); - */ - return 0; -} +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/script-functions.h" + +/* + int OnJoin(int id, int writesocket) + id - Who joins + Return Values: + 0 - OK + */ +int OnJoin(int id, int writesocket) +{ + SendJoinMessage(id, writesocket); + printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); + return 0; +} + +/* + int OnLeave(int id, int writesocket) + id - Who leaves + Return Values: + 0 - OK + */ +int OnLeave(int id, int writesocket) +{ + SendLeaveMessage(id, writesocket); + printf("%s has left the game!\n", player[id].name); + return 0; +} + +/* + int OnSpecmove(int id, int newx, int newy, int writesocket) + Return Values: + 0 - OK + 1 - Don't save it + */ + +int OnSpecmove(int id, int newx, int newy, int writesocket) +{ + return 0; +} + +/* + int OnServerstart() + Return Values: + 0 - OK + */ +int OnServerStart() +{ + time_t rawtime; + time(&rawtime); + printf("********** Server started **********\n"); + printf("%s", ctime(&rawtime)); + return 0; +} + +/* + int OnExit() + Return Values: + 0 - OK + */ +int OnExit() +{ + printf("********** Server Shutdown! **********\n\n\n\n\n"); + return 0; +} + +/* + int OnRespawnRequest(int id, int writesocket) + Return Values: + 0 - Respawn + 1 - Don't Respawn + */ +int OnRespawnRequest(int id, int writesocket) +{ + if (player[id].dead == 1) + return 0; + else + return 1; +} + +/* + int OnRespawn(int id, int writesocket) + Return Values: + 0 - OK + */ +int OnRespawn(int id, int writesocket) +{ + return 0; +} + +/* + int OnRespawn(int id, int writesocket) + Return Values: + 0 - OK + */ +int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) +{ + int i; + for (i = 0; i <= 9; i++) + { + if (player[id].slot[i].id == wpnid) + { + player[id].actualweapon = i; + if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) + { + player[id].zoommode = 0; + } + player[id].reloading = 0; + + printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); + return 0; + } + } + return 1; +} + +/* + int OnAdvancedFire(int id, int status, int writesocket) + Return Values: + 0 - OK + 1 - Not OK + */ +int OnAdvancedFire(int id, int status, int writesocket) +{ + int wpnid = player[id].slot[player[id].actualweapon].id; + + int temptime = mtime(); + if (temptime < player[id].zoomtimer) + { + printf("Zoomtimer error!\n"); + return 1; + } + else + { + player[id].zoomtimer = mtime() + 500; + } + + switch (weapons[wpnid].special) + { + case 0: + printf("%s tried to hack!\n", player[id].name); + return 1; + case 1: + case 2: + { + if (status <= 1) + { + player[id].zoommode = status; + break; + } + return 1; + } + case 3: + { + player[id].zoommode = 1; + OnFire(id, writesocket); + player[id].zoommode = 0; + break; + } + case 4: + { + if (status <= 1) + { + player[id].zoommode = status; + break; + } + return 1; + } + case 5: + { + if (status <= 2 && player[id].zoommode + 1 == status) + { + player[id].zoommode = status; + break; + } + else if (player[id].zoommode == 2) + { + player[id].zoommode = 0; + break; + } + return 1; + } + default: + { + SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); + return 1; + } + + } + + return 0; +} +/* + int OnFire(int id, int writesocket) + Return Values: + 0 - OK + 1 - Not OK + */ +int OnFire(int id, int writesocket) +{ + //printf("%s tried to shoot!\n", player[id].name); + short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; + if (*ammo1 <= 0 && *ammo1 != -1) + { + printf("Not enough ammo!\n"); + return 1; + } + else + { + if (*ammo1 != -1) + { + *ammo1 = *ammo1 - 1; + } + } + int temptime = mtime(); + if (temptime < player[id].firetimer) + { + printf("Firetimer error!\n"); + return 1; + } + else + { + player[id].firetimer = mtime() + + weapons[player[id].slot[player[id].actualweapon].id].freq; + } + + int i; + int range = weapons[player[id].slot[player[id].actualweapon].id].range; + + int startx = player[id].x; + int starty = player[id].y; + float rotx; + float roty; + float temprot = player[id].rotation; + + short playershit[MAX_CLIENTS] = + { 0 }; + + if (temprot < 0) + { + temprot = 360 - (temprot * -1); + } + temprot = 360 - temprot; + + temprot += 90; + if (temprot > 360) + { + temprot = temprot - 360; + } + + rotx = cos((temprot) * PI / 180); + roty = sin((temprot) * PI / 180); + + for (i = 1; i <= range; i++) + { + startx += i * rotx; + starty -= i * roty; + + int tilex = (int) (startx) / 32; + int tiley = (int) (starty) / 32; + + if (tilex <= 0 || tiley <= 0) + break; + int tilemode = map[tilex][tiley].mode; + if (tilemode == 1 || tilemode == 3 || tilemode == 4) + { + break; + } + + int b; + for (b = 1; b <= sv_maxplayers; b++) + { + if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id + && player[b].dead == 0 && playershit[b] == 0 + && player[id].team != player[b].team) + { + if (sqrt((player[b].x - startx) * (player[b].x - startx) + + (player[b].y - starty) * (player[b].y - starty)) + <= 16) + { + OnHit(id, b, writesocket); + playershit[b] = 1; + } + } + } + } + return 0; +} +/* + int OnHit(int hitter, int victim, int writesocket) + Return Values: + 0 - OK + */ +int OnHit(int hitter, int victim, int writesocket) +{ + int wpnid = player[hitter].slot[player[hitter].actualweapon].id; + int damage; + switch (player[hitter].zoommode) + { + case 0: + damage = weapons[wpnid].weapondamage; + break; + case 1: + damage = weapons[wpnid].weapondamage_z1; + break; + case 2: + damage = weapons[wpnid].weapondamage_z2; + break; + default: + damage = weapons[wpnid].weapondamage; + break; + } + if (player[victim].health - damage > 0) + { + player[victim].health -= damage; + SendHitMessage(victim, hitter, player[victim].health, writesocket); + printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); + } + else + { + OnKill(hitter, victim, wpnid, writesocket); + } + + return 0; +} + +int OnBuyAttempt(int id, int wpnid, int writesocket) +{ + + int i; + for (i = 0; i <= 99; i++) + { + if (weapons[wpnid].name != NULL) //test if weapon available + { + if (player[id].money - weapons[wpnid].price >= 0) + { + if (weapons[wpnid].team == 0 || weapons[wpnid].team + == player[id].team) //Check if he is in the right team to buy this weapon + { + if (player[id].team == 1) + { + //Check if in buyzone + int b; + for (b = 0; b <= tspawncount; b++) + { + int playerx = player[id].x; + int playery = player[id].y; + int tempx = tspawnx[b] * 32; + int tempy = tspawny[b] * 32; + //If player in buyzone (5*5) + if (playerx >= tempx - 64 && playerx <= tempx + 64 + && playery >= tempy - 64 && playery + <= tempy + 64) + { + return 0; + } + } + SendBuyFailedMessage(id, 255, writesocket); + return 1; + } + else if (player[id].team == 2) + { + int b; + for (b = 0; b <= ctspawncount; b++) + { + int playerx = player[id].x; + int playery = player[id].y; + int tempx = ctspawnx[b] * 32; + int tempy = ctspawny[b] * 32; + //If player in buyzone (5*5) + if (playerx >= tempx - 64 && playerx <= tempx + 64 + && playery >= tempy - 64 && playery + <= tempy + 64) + { + return 0; + } + } + SendBuyFailedMessage(id, 255, writesocket); + return 1; + } + } + else + { + SendBuyFailedMessage(id, 252, writesocket); + return 1; + } + } + else + { + SendBuyFailedMessage(id, 253, writesocket); + return 1; + } + } + } + //if nothing found + SendBuyFailedMessage(id, 244, writesocket); + /* + * 242 nothing + * 243 Grenade rebuying is not allowed at this server + * 244 it's not allowed to buy that weapon at this server + * 245 you can't carry more of this + * 246 you can't carry more of this + * 247 you can't carry an additional weapon + * 248 you can't buy more ammo + * 249 you are not allowed to buy anything + * 250 buying is not allowed + * 251 you have already this or something better + * 252 you can't buy this item; + * 253 insufficient fund; + * 254 buytime passed; + * 255 you are not in a buyzone + */ + return 1; +} + +int OnBuy(int id, int wpnid, int writesocket) +{ + player[id].money -= weapons[wpnid].price; + player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot + printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); + return 0; +} + +int OnKill(int hitter, int victim, int wpnid, int writesocket) +{ + player[victim].health = 0; + player[victim].dead = 1; + player[hitter].score++; + player[hitter].kills++; + player[victim].deaths++; + RemoveAllPlayerWeapon(victim); + SendHitMessage(victim, hitter, player[victim].health, writesocket); + printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); + return 0; +} +/* + int OnChatMessage(int id, unsigned char *message, int team, int writesocket) + Return Values: + 0 - OK + */ +int OnChatMessage(int id, unsigned char *message, int team, int writesocket) +{ + if (team == 1) + { + printf("%s: %s\n", player[id].name, message); + } + else if (team == 2) + { + printf("%s (Team): %s\n", player[id].name, message); + } + SendChatMessage(id, message, team, writesocket); + return 0; +} + +/* + int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) + Return Values: + 0 - OK + 1 - Don't join + */ +int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, + int writesocket) +{ + return 0; +} + +/* + int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) + Return Values: + 0 - OK + */ +int OnTeamChange(int id, unsigned char team, unsigned char skin, + int writesocket) +{ + if (skin != 5) + { + switch (team) + { + case 0: + printf("%s is now spectator\n", player[id].name); + break; + case 1: + printf("%s is now terrorist\n", player[id].name); + break; + case 2: + printf("%s is now counter-terrorist\n", player[id].name); + break; + default: + printf("%s joined a unknown team\n", player[id].name); + break; + } + SendHitMessage(id, id, 0, writesocket); + player[id].dead = 1; + RemoveAllPlayerWeapon(id); + } + if (team <= 2) + { + SendTeamChangeMessage(id, team, skin, writesocket); + } + return 0; +} + +/* + int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) + Return Values: + 0 - OK + 1 - Don't move + */ +int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, + int writesocket) +{ + /* + int newx = (int)ceil((x)/32); + int newy = (int)ceil((y)/32); + printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); + */ + return 0; +} diff --git a/src/sendto_functions.c b/src/sendto_functions.c index dad1a45..0b902aa 100644 --- a/src/sendto_functions.c +++ b/src/sendto_functions.c @@ -1,77 +1,77 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/sendto_functions.h" - -void SendToPlayer(unsigned char *message, int length, int id, int reliable, - int writesocket) -{ - struct sockaddr_in tempclient; - tempclient.sin_family = AF_INET; - tempclient.sin_port = player[id].port; - tempclient.sin_addr = player[id].ip; - unsigned char *buffer = malloc(length + 2); - if (buffer == NULL) - error_exit("Memory error ( SendToPlayer() )"); - - if (reliable == 1) - { - unsigned short *pNummer = &player[id].server_nummer; - memcpy(buffer, pNummer, sizeof(unsigned short)); - player[id].server_nummer += 2; - } - else if (reliable == 0) - { - player[id].server_nummer--; - unsigned short *pNummer = &player[id].server_nummer; - memcpy(buffer, pNummer, sizeof(unsigned short)); - player[id].server_nummer++; - } - memcpy(buffer + 2, message, length); - udp_send(writesocket, buffer, length + 2, &tempclient); -} - -void SendToAll(unsigned char *message, int length, int reliable, - int writesocket) -{ - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && player[i].joinstatus >= 4) - { - SendToPlayer(message, length, i, reliable, writesocket); - } - } -} - -void SendToTeam(unsigned char *message, int length, int reliable, int team, - int writesocket) -{ - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && player[i].joinstatus >= 4 && player[i].team - == team) - { - SendToPlayer(message, length, i, reliable, writesocket); - } - } -} - -void SendToAllOther(int id, unsigned char *message, int length, int reliable, - int writesocket) -{ - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && player[i].joinstatus >= 4 && i != id) - { - SendToPlayer(message, length, i, reliable, writesocket); - } - } -} +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/sendto_functions.h" + +void SendToPlayer(unsigned char *message, int length, int id, int reliable, + int writesocket) +{ + struct sockaddr_in tempclient; + tempclient.sin_family = AF_INET; + tempclient.sin_port = player[id].port; + tempclient.sin_addr = player[id].ip; + unsigned char *buffer = malloc(length + 2); + if (buffer == NULL) + error_exit("Memory error ( SendToPlayer() )"); + + if (reliable == 1) + { + unsigned short *pNummer = &player[id].server_nummer; + memcpy(buffer, pNummer, sizeof(unsigned short)); + player[id].server_nummer += 2; + } + else if (reliable == 0) + { + player[id].server_nummer--; + unsigned short *pNummer = &player[id].server_nummer; + memcpy(buffer, pNummer, sizeof(unsigned short)); + player[id].server_nummer++; + } + memcpy(buffer + 2, message, length); + udp_send(writesocket, buffer, length + 2, &tempclient); +} + +void SendToAll(unsigned char *message, int length, int reliable, + int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } +} + +void SendToTeam(unsigned char *message, int length, int reliable, int team, + int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4 && player[i].team + == team) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } +} + +void SendToAllOther(int id, unsigned char *message, int length, int reliable, + int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4 && i != id) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } +} diff --git a/src/settings.c b/src/settings.c index 6d8d75c..07ce690 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,171 +1,171 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, GuccaGucca */ #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; char startweapons[] = {50}; unsigned char *sv_name = NULL; unsigned char *sv_map = NULL; unsigned int sv_hostport = 0; unsigned short sv_maxplayers = 0; unsigned short sv_fow = 0; unsigned short sv_gamemode = 0; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; unsigned char *sv_password = 0; unsigned short bot_count = 0; unsigned short mp_roundtime = 0; unsigned short mp_freezetime = 0; unsigned short mp_c4timer = 0; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; unsigned short mp_specmode = 0; unsigned short onlineplayer = 0; unsigned short mp_startmoney = 0; struct setting { char *name; char *value; }; int tointeger(char * c); double todouble(char *c); struct setting * settings[256]; int entries; int readConfig() { FILE * pFile; char s[256]; int setting_num = 0; pFile = fopen("server.cfg","r"); if(pFile == NULL) perror("Error opening file: server.cfg"); else { while((fgets(s,sizeof(s),pFile))!= NULL) { if(s[0]=='\n' || (s[0] == '/' && s[1] == '/')) continue; //char *s1,*s2,*type; int i; for(i = 0; i < strlen(s);i++) { if(s[i] == ' ') { i++; //skip ' ' char struct setting * var; var = (struct setting*)malloc(sizeof(struct setting)); var->name = malloc(i+1); if(var->name == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->name,s,i); var->name[i] = '\0'; if(s[strlen(s)-i-1] == '\n') //if \n found then remove it { var->value = malloc(strlen(s)-i-1 +1); if(var->value == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->value,&s[i],strlen(s)-i-1); //also ommit the \n var->value[strlen(s)-i-1] = '\0'; } else { var->value = malloc(strlen(s)-i +1); if(var->value == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->value,&s[i],strlen(s)-i); //also ommit the \n var->value[strlen(s)-i] = '\0'; } settings[setting_num] = var; break; } } setting_num++; } fclose(pFile); } return setting_num; } char *GetValue(char *sname, char *alternate)////struct setting ** arr , int length) { int i; for(i = 0; i < entries; i++) { if(settings[i] != NULL) { struct setting *var = settings[i]; if(strcmp(var->name,sname)==0) { char *string = malloc(strlen(var->value)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, var->value, strlen(var->value)); string[strlen(var->value)] = '\0'; free(var->name); free(var->value); free(var); //also frees settings[i] settings[i] = NULL; return string; } } } //If not found char *string = malloc(strlen(alternate)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, alternate, strlen(alternate)); string[strlen(alternate)] = '\0'; return string; // doesn't exist } void ReadCfg() { entries = readConfig(); sv_name = (unsigned char *)GetValue("sv_name", "Alpha Custom CS2D Server"); sv_map = (unsigned char *)GetValue("sv_map", "de_cs2d"); sv_hostport = tointeger(GetValue("sv_hostport", "36963")); sv_maxplayers = tointeger(GetValue("sv_maxplayers", "32")) +1; sv_fow = tointeger(GetValue("sv_fow", "0")); sv_gamemode = tointeger(GetValue("sv_gamemode", "2")); sv_friendlyfire = tointeger(GetValue("sv_friendlyfire", "0")); sv_usgnonly = tointeger(GetValue("sv_usgnonly", "0")); sv_password = (unsigned char *)GetValue("sv_password", ""); bot_count = tointeger(GetValue("bot_count", "0")); mp_roundtime = tointeger(GetValue("mp_roundtime", "5")); mp_freezetime = tointeger(GetValue("mp_freezetime", "0")); mp_c4timer = tointeger(GetValue("mp_c4timer", "35")); mp_infammo = tointeger(GetValue("mp_infammo", "0")); mp_respawndelay = tointeger(GetValue("mp_respawndelay", "0")); mp_specmode = tointeger(GetValue("mp_specmode", "0")); - mp_startmoney = tointeger(GetValue("mp_startmoney", "65000")); + mp_startmoney = tointeger(GetValue("mp_startmoney", "1000")); } int tointeger(char *c) { int buff = atoi(c); free(c); return buff; } double todouble(char *c) { double buff = atof(c); free(c); return buff; } diff --git a/src/weapons.c b/src/weapons.c index d9d4629..222ae25 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,65 +1,65 @@ -/* - * Published under GPLv3. - * For more information take a look at the Readme - * Copyright (c) by the authors of this file - * - * Author/s of this file: Jermuk - */ - -#include "../include/weapons.h" - -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, - short wpndmg_z2, short freq, short speed, short slot, short price, - short range, short accuracy, short ammo1, short ammo2, int reloadtime, - short special, short team) -{ - if (name != NULL) - { - weapons[id].name = malloc(strlen(name) + 1); - if (weapons[id].name == NULL) - error_exit("Memory Error in AddWeapon()\n"); - strncpy(weapons[id].name, name, strlen(name) + 1); - } - else - { - weapons[id].name = NULL; - } - weapons[id].weapondamage = wpndmg; - weapons[id].weapondamage_z1 = wpndmg_z1; - weapons[id].weapondamage_z2 = wpndmg_z2; - if(freq != 0) - weapons[id].freq = (short)(1/freq)*60*1000; - else - weapons[id].freq = 1000; - weapons[id].speed = speed; - weapons[id].slot = slot; - weapons[id].price = price; - weapons[id].range = range; - weapons[id].accuracy = accuracy; - weapons[id].ammo1 = ammo1; - weapons[id].ammo2 = ammo2; - weapons[id].reloadtime = reloadtime; - weapons[id].special = special; - weapons[id].team = team; -} -void WeaponInit() -{ - int i; - for(i = 0; i <= 99; i++) - { - AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0); - } - AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000, 1, 0); - AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000, 2, 0); - AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000, 0, 0); - AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000, 0, 0); - AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000, 0, 0); - AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000, 0, 0); - AddWeapon(20,"MP5" , 13 , 0, 0, 500 , 1, 1,1500, 300, 2 , 30, 120, 1000, 0, 0); - AddWeapon(21,"TMP" , 9 , 0, 0, 750 , 1, 1,1250, 100, 4 , 30, 120, 1000, 0, 2); - AddWeapon(22,"P90" , 11 , 0, 0, 750 , 1, 1,2350, 300, 3 , 50, 100, 1000, 0, 2); - AddWeapon(35, "AWP" , 50 , 65 , 150, 23 , 3, 1, 4750 , 400, 0 , 10, 30, 2000, 5, 0); - AddWeapon(50, "Knife", 50, 100, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0, 3, 0); -} - - +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + +#include "../include/weapons.h" + +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, + short wpndmg_z2, short freq, short speed, short slot, short price, + short range, short accuracy, short ammo1, short ammo2, int reloadtime, + short special, short team) +{ + if (name != NULL) + { + weapons[id].name = malloc(strlen(name) + 1); + if (weapons[id].name == NULL) + error_exit("Memory Error in AddWeapon()\n"); + strncpy(weapons[id].name, name, strlen(name) + 1); + } + else + { + weapons[id].name = NULL; + } + weapons[id].weapondamage = wpndmg; + weapons[id].weapondamage_z1 = wpndmg_z1; + weapons[id].weapondamage_z2 = wpndmg_z2; + if(freq != 0) + weapons[id].freq = (short)(1/freq)*60*1000; + else + weapons[id].freq = 1000; + weapons[id].speed = speed; + weapons[id].slot = slot; + weapons[id].price = price; + weapons[id].range = range; + weapons[id].accuracy = accuracy; + weapons[id].ammo1 = ammo1; + weapons[id].ammo2 = ammo2; + weapons[id].reloadtime = reloadtime; + weapons[id].special = special; + weapons[id].team = team; +} +void WeaponInit() +{ + int i; + for(i = 0; i <= 99; i++) + { + AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0); + } + AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000, 1, 0); + AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000, 2, 0); + AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000, 0, 0); + AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000, 0, 0); + AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000, 0, 0); + AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000, 0, 0); + AddWeapon(20,"MP5" , 13 , 0, 0, 500 , 1, 1,1500, 300, 2 , 30, 120, 1000, 0, 0); + AddWeapon(21,"TMP" , 9 , 0, 0, 750 , 1, 1,1250, 100, 4 , 30, 120, 1000, 0, 2); + AddWeapon(22,"P90" , 11 , 0, 0, 750 , 1, 1,2350, 300, 3 , 50, 100, 1000, 0, 2); + AddWeapon(35, "AWP" , 50 , 65 , 150, 23 , 3, 1, 4750 , 400, 0 , 10, 30, 2000, 5, 0); + AddWeapon(50, "Knife", 50, 100, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0, 3, 0); +} + +
Jermuk/custom_cs2dsrv
044290b9a833b73ee81fd507f22e0b84070317ab
Fixed '\n' bug
diff --git a/.gitignore b/.gitignore index b472645..ee50cdf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,11 @@ html Debug .settings .cproject .project doxygen.Doxyfile *.txt Release/src *.map -*.cfg \ No newline at end of file +*.cfg +notices \ No newline at end of file diff --git a/src/log.c b/src/log.c index 94bba26..fed5343 100644 --- a/src/log.c +++ b/src/log.c @@ -1,90 +1,90 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/log.h" /** * \fn void myprintf(char *string, ...) * \brief prints string with time to stdout and logfile * \param *string the string to print out (same syntax as printf) * \param ... the other parameters, if necessary */ void myprintf(char *string, ...) { #ifdef _WIN32 FILE *logfile; time_t rawtime; struct tm * timeinfo; logfile = fopen("log.txt", "a+"); if (logfile != NULL) { time(&rawtime); timeinfo = localtime(&rawtime); - //fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string, argzeiger); - //vfprintf(logfile, string, argzeiger); + vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } #else time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); va_end(argzeiger); #endif } /** * \fn void myprintf2(char *string, ...) * \brief same as myprintf, just with the difference, that the time won't be printed * \param *string the string to print out (same syntax as printf) * \param ... the other parameters, if necessary */ void myprintf2(char *string, ...) { #ifdef _WIN32 FILE *logfile; logfile = fopen("log.txt", "a+"); if (logfile != NULL) { va_list argzeiger; va_start(argzeiger,string); vprintf(string, argzeiger); vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } #else va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); va_end(argzeiger); #endif } diff --git a/src/settings.c b/src/settings.c index bc8563c..6d8d75c 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,159 +1,171 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk, GuccaGucca */ #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; char startweapons[] = {50}; unsigned char *sv_name = NULL; unsigned char *sv_map = NULL; unsigned int sv_hostport = 0; unsigned short sv_maxplayers = 0; unsigned short sv_fow = 0; unsigned short sv_gamemode = 0; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; unsigned char *sv_password = 0; unsigned short bot_count = 0; unsigned short mp_roundtime = 0; unsigned short mp_freezetime = 0; unsigned short mp_c4timer = 0; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; unsigned short mp_specmode = 0; unsigned short onlineplayer = 0; unsigned short mp_startmoney = 0; struct setting { char *name; char *value; }; int tointeger(char * c); double todouble(char *c); struct setting * settings[256]; int entries; int readConfig() { FILE * pFile; char s[256]; int setting_num = 0; pFile = fopen("server.cfg","r"); if(pFile == NULL) perror("Error opening file: server.cfg"); else { while((fgets(s,sizeof(s),pFile))!= NULL) { if(s[0]=='\n' || (s[0] == '/' && s[1] == '/')) continue; //char *s1,*s2,*type; int i; for(i = 0; i < strlen(s);i++) { if(s[i] == ' ') { + i++; //skip ' ' char struct setting * var; var = (struct setting*)malloc(sizeof(struct setting)); var->name = malloc(i+1); if(var->name == NULL) error_exit("Memory error in readConfig()\n"); strncpy(var->name,s,i); var->name[i] = '\0'; - var->value = malloc(strlen(s)-i-1 +1); - if(var->value == NULL) error_exit("Memory error in readConfig()\n"); - strncpy(var->value,&s[i],strlen(s)-i-1); //also ommit the \n - var->value[strlen(s)-i-1] = '\0'; + if(s[strlen(s)-i-1] == '\n') //if \n found then remove it + { + var->value = malloc(strlen(s)-i-1 +1); + if(var->value == NULL) error_exit("Memory error in readConfig()\n"); + strncpy(var->value,&s[i],strlen(s)-i-1); //also ommit the \n + var->value[strlen(s)-i-1] = '\0'; + } + else + { + var->value = malloc(strlen(s)-i +1); + if(var->value == NULL) error_exit("Memory error in readConfig()\n"); + strncpy(var->value,&s[i],strlen(s)-i); //also ommit the \n + var->value[strlen(s)-i] = '\0'; + } + settings[setting_num] = var; break; } } setting_num++; } fclose(pFile); } return setting_num; } char *GetValue(char *sname, char *alternate)////struct setting ** arr , int length) { int i; for(i = 0; i < entries; i++) { if(settings[i] != NULL) { struct setting *var = settings[i]; if(strcmp(var->name,sname)==0) { char *string = malloc(strlen(var->value)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, var->value, strlen(var->value)); string[strlen(var->value)] = '\0'; free(var->name); free(var->value); free(var); //also frees settings[i] settings[i] = NULL; return string; } } } //If not found char *string = malloc(strlen(alternate)+1); if(string == NULL) error_exit("Memory error in GetValue()\n"); strncpy(string, alternate, strlen(alternate)); string[strlen(alternate)] = '\0'; return string; // doesn't exist } void ReadCfg() { entries = readConfig(); sv_name = (unsigned char *)GetValue("sv_name", "Alpha Custom CS2D Server"); sv_map = (unsigned char *)GetValue("sv_map", "de_cs2d"); sv_hostport = tointeger(GetValue("sv_hostport", "36963")); sv_maxplayers = tointeger(GetValue("sv_maxplayers", "32")) +1; sv_fow = tointeger(GetValue("sv_fow", "0")); sv_gamemode = tointeger(GetValue("sv_gamemode", "2")); sv_friendlyfire = tointeger(GetValue("sv_friendlyfire", "0")); sv_usgnonly = tointeger(GetValue("sv_usgnonly", "0")); sv_password = (unsigned char *)GetValue("sv_password", ""); bot_count = tointeger(GetValue("bot_count", "0")); mp_roundtime = tointeger(GetValue("mp_roundtime", "5")); mp_freezetime = tointeger(GetValue("mp_freezetime", "0")); mp_c4timer = tointeger(GetValue("mp_c4timer", "35")); mp_infammo = tointeger(GetValue("mp_infammo", "0")); mp_respawndelay = tointeger(GetValue("mp_respawndelay", "0")); mp_specmode = tointeger(GetValue("mp_specmode", "0")); mp_startmoney = tointeger(GetValue("mp_startmoney", "65000")); } int tointeger(char *c) { int buff = atoi(c); free(c); return buff; } double todouble(char *c) { double buff = atof(c); free(c); return buff; }
Jermuk/custom_cs2dsrv
db70c9eb85c18d9506979e1594e5e6a4d36305d6
Added CFG Parser and changed Readme
diff --git a/.gitignore b/.gitignore index 85f5ac0..b472645 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ html Debug .settings .cproject .project doxygen.Doxyfile *.txt Release/src *.map +*.cfg \ No newline at end of file diff --git a/Readme b/Readme index 0df188f..5a003d2 100644 --- a/Readme +++ b/Readme @@ -1,27 +1,27 @@ Custom Counter Strike 2D Server a0.1 Copyright (C) 2010 by the authors of their respective files This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; -if not, see <http://www.gnu.org/licenses/>. +if not, see <http://www.gnu.org/licenses/ >. If you want to help me or you have questions contact me via Unrealsoftware-PM (Jermuk) or E-Mail < JExRMxUK (at)JExRMxUK (dot) DE > (Without x) Notice to windows: -If you get linker errors, try to include the library libwsock32. +If you get linker errors, try to include the library libwsock32 or ws2_32.lib. Credits: - Main coder: Jermuk aka DÖNARMASTER from <www.Kebab-Clan.de> Thanks to: - Rynti and PopUp for helping me to write the OnFire routine - Rynti for helping me to encrypt cs2d's packet structure - DC, without him, I never understood cs2d's packet structure \ No newline at end of file diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe index 89984be..1913a95 100644 Binary files a/Release/custom_cs2dsrv.exe and b/Release/custom_cs2dsrv.exe differ diff --git a/include/settings.h b/include/settings.h index 87ce571..23d3684 100644 --- a/include/settings.h +++ b/include/settings.h @@ -1,44 +1,49 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * - * Author/s of this file: Jermuk + * Author/s of this file: Jermuk, GuccaGucca */ #ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED +#include "../include/main.h" + #define MAX_BUF 1024 /* --- Server Settings --- */ #define LOCAL_PORT 1994 #define MAX_CLIENTS 64 #define TIMEOUT 10 +#define SETTINGS_PATH "server.cfg" extern unsigned char pre_authcode[]; -extern unsigned char sv_name[]; -extern unsigned char sv_map[]; +extern unsigned char *sv_name; +extern unsigned char *sv_map; extern unsigned int sv_hostport; extern unsigned short sv_maxplayers; extern unsigned short sv_fow; extern unsigned short sv_gamemode; extern unsigned short sv_friendlyfire; extern unsigned short sv_usgnonly; -extern unsigned char sv_password[]; +extern unsigned char *sv_password; extern unsigned short bot_count; extern unsigned short mp_roundtime; extern unsigned short mp_freezetime; extern unsigned short mp_c4timer; extern unsigned short mp_infammo; extern unsigned short mp_respawndelay; extern unsigned short mp_specmode; extern unsigned short onlineplayer; extern unsigned short mp_startmoney; -#define STARTWEAPONS_COUNT 2 +#define STARTWEAPONS_COUNT 1 extern char startweapons[]; +void ReadCfg(); + #endif // SETTINGS_H_INCLUDED diff --git a/include/structs.h b/include/structs.h index bc9fa17..e9ac3c3 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,102 +1,102 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" - +#define MAX_CLIENTS 64 struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; short freq; //every freq ms one shoot short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; short special; short team; }; /* * team * 0 - everyone can buy it * 1 - t-only * 2 - ct only * 3 - unbuyable */ struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; short special; }; /* * special * 0 = Normal * 1 = Silencer * 2 = Burst * 3 = Melee * 4 = 1xZoom * 5 = 2xZoom * 6 = Shotgun */ struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; time_t lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; unsigned short deaths; short score; unsigned short x, y; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; unsigned short kills; int reloadtimer, reloading; short dead; int start; unsigned short latency; int firetimer, zoomtimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/src/main.c b/src/main.c index 2cbe81e..df01197 100644 --- a/src/main.c +++ b/src/main.c @@ -1,253 +1,254 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * * Author/s of this file: Jermuk */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); + ReadCfg(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); while (1) { CheckForTimeout(readsocket); PingAllPlayer(readsocket, &firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); select(readsocket + 1, &descriptor, NULL, NULL, NULL); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: rtn = advanced_fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return EXIT_SUCCESS; } diff --git a/src/settings.c b/src/settings.c index 71b722c..bc8563c 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,33 +1,159 @@ /* * Published under GPLv3. * For more information take a look at the Readme * Copyright (c) by the authors of this file * - * Author/s of this file: Jermuk + * Author/s of this file: Jermuk, GuccaGucca */ #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; +char startweapons[] = {50}; -unsigned char sv_name[] = "Alpha Custom CS2D Server"; -unsigned char sv_map[] = "de_cs2d"; -unsigned int sv_hostport = 1994; -unsigned short sv_maxplayers = 32 +1; +unsigned char *sv_name = NULL; +unsigned char *sv_map = NULL; +unsigned int sv_hostport = 0; +unsigned short sv_maxplayers = 0; unsigned short sv_fow = 0; -unsigned short sv_gamemode = 2; +unsigned short sv_gamemode = 0; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; -unsigned char sv_password[] = ""; +unsigned char *sv_password = 0; unsigned short bot_count = 0; -unsigned short mp_roundtime = 5; +unsigned short mp_roundtime = 0; unsigned short mp_freezetime = 0; -unsigned short mp_c4timer = 35; +unsigned short mp_c4timer = 0; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; -unsigned short mp_specmode = 1; +unsigned short mp_specmode = 0; unsigned short onlineplayer = 0; -unsigned short mp_startmoney = 65000; +unsigned short mp_startmoney = 0; -char startweapons[] = {50, 35}; + +struct setting +{ + char *name; + char *value; +}; + +int tointeger(char * c); +double todouble(char *c); +struct setting * settings[256]; +int entries; + +int readConfig() +{ + FILE * pFile; + char s[256]; + int setting_num = 0; + pFile = fopen("server.cfg","r"); + + if(pFile == NULL) perror("Error opening file: server.cfg"); + else + { + while((fgets(s,sizeof(s),pFile))!= NULL) + { + if(s[0]=='\n' || (s[0] == '/' && s[1] == '/')) + continue; + //char *s1,*s2,*type; + + int i; + for(i = 0; i < strlen(s);i++) + { + if(s[i] == ' ') + { + struct setting * var; + var = (struct setting*)malloc(sizeof(struct setting)); + + var->name = malloc(i+1); + if(var->name == NULL) error_exit("Memory error in readConfig()\n"); + strncpy(var->name,s,i); + var->name[i] = '\0'; + var->value = malloc(strlen(s)-i-1 +1); + if(var->value == NULL) error_exit("Memory error in readConfig()\n"); + strncpy(var->value,&s[i],strlen(s)-i-1); //also ommit the \n + var->value[strlen(s)-i-1] = '\0'; + + settings[setting_num] = var; + break; + } + } + setting_num++; + } + fclose(pFile); + } + return setting_num; +} + +char *GetValue(char *sname, char *alternate)////struct setting ** arr , int length) +{ + int i; + for(i = 0; i < entries; i++) + { + if(settings[i] != NULL) + { + struct setting *var = settings[i]; + if(strcmp(var->name,sname)==0) + { + char *string = malloc(strlen(var->value)+1); + if(string == NULL) error_exit("Memory error in GetValue()\n"); + strncpy(string, var->value, strlen(var->value)); + string[strlen(var->value)] = '\0'; + + free(var->name); + free(var->value); + free(var); //also frees settings[i] + settings[i] = NULL; + return string; + } + } + + } + //If not found + char *string = malloc(strlen(alternate)+1); + if(string == NULL) error_exit("Memory error in GetValue()\n"); + strncpy(string, alternate, strlen(alternate)); + string[strlen(alternate)] = '\0'; + + return string; // doesn't exist +} + +void ReadCfg() +{ + entries = readConfig(); + + sv_name = (unsigned char *)GetValue("sv_name", "Alpha Custom CS2D Server"); + sv_map = (unsigned char *)GetValue("sv_map", "de_cs2d"); + sv_hostport = tointeger(GetValue("sv_hostport", "36963")); + sv_maxplayers = tointeger(GetValue("sv_maxplayers", "32")) +1; + sv_fow = tointeger(GetValue("sv_fow", "0")); + sv_gamemode = tointeger(GetValue("sv_gamemode", "2")); + sv_friendlyfire = tointeger(GetValue("sv_friendlyfire", "0")); + sv_usgnonly = tointeger(GetValue("sv_usgnonly", "0")); + sv_password = (unsigned char *)GetValue("sv_password", ""); + bot_count = tointeger(GetValue("bot_count", "0")); + + mp_roundtime = tointeger(GetValue("mp_roundtime", "5")); + mp_freezetime = tointeger(GetValue("mp_freezetime", "0")); + mp_c4timer = tointeger(GetValue("mp_c4timer", "35")); + mp_infammo = tointeger(GetValue("mp_infammo", "0")); + mp_respawndelay = tointeger(GetValue("mp_respawndelay", "0")); + mp_specmode = tointeger(GetValue("mp_specmode", "0")); + mp_startmoney = tointeger(GetValue("mp_startmoney", "65000")); +} + +int tointeger(char *c) +{ + int buff = atoi(c); + free(c); + return buff; +} + +double todouble(char *c) +{ + double buff = atof(c); + free(c); + return buff; +}
Jermuk/custom_cs2dsrv
afda6fa3a4ad8002884d17dd9fe2d9cc252af6b5
Little Readme change (made the e-mail bot safe)
diff --git a/Readme b/Readme index 00ac732..0df188f 100644 --- a/Readme +++ b/Readme @@ -1,27 +1,27 @@ Custom Counter Strike 2D Server a0.1 Copyright (C) 2010 by the authors of their respective files This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you want to help me or you have questions -contact me via Unrealsoftware-PM (Jermuk) or E-Mail <[email protected]> +contact me via Unrealsoftware-PM (Jermuk) or E-Mail < JExRMxUK (at)JExRMxUK (dot) DE > (Without x) Notice to windows: If you get linker errors, try to include the library libwsock32. Credits: - Main coder: Jermuk aka DÖNARMASTER from <www.Kebab-Clan.de> Thanks to: - Rynti and PopUp for helping me to write the OnFire routine - Rynti for helping me to encrypt cs2d's packet structure - DC, without him, I never understood cs2d's packet structure \ No newline at end of file
Jermuk/custom_cs2dsrv
da60f8803d8b0166b41a6374f411df005c4900e6
Fix and Add Release Fixed: - PingAllPlayer() problem - Firetimer problem - better source code formatting now
diff --git a/Readme b/Readme new file mode 100644 index 0000000..00ac732 --- /dev/null +++ b/Readme @@ -0,0 +1,27 @@ +Custom Counter Strike 2D Server a0.1 + +Copyright (C) 2010 by the authors of their respective files + +This program is free software; you can redistribute it and/or modify it under the +terms of the GNU General Public License as published by the Free Software Foundation; +either version 3 of the License, or (at your option) any later version. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with this program; +if not, see <http://www.gnu.org/licenses/>. + + +If you want to help me or you have questions +contact me via Unrealsoftware-PM (Jermuk) or E-Mail <[email protected]> + +Notice to windows: +If you get linker errors, try to include the library libwsock32. + +Credits: +- Main coder: Jermuk aka DÖNARMASTER from <www.Kebab-Clan.de> + +Thanks to: +- Rynti and PopUp for helping me to write the OnFire routine +- Rynti for helping me to encrypt cs2d's packet structure +- DC, without him, I never understood cs2d's packet structure \ No newline at end of file diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe index 8f715fb..89984be 100644 Binary files a/Release/custom_cs2dsrv.exe and b/Release/custom_cs2dsrv.exe differ diff --git a/include/cross_layer.h b/include/cross_layer.h index 934fdd2..d8eef64 100644 --- a/include/cross_layer.h +++ b/include/cross_layer.h @@ -1,13 +1,23 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef CROSS_LAYER_H_INCLUDED #define CROSS_LAYER_H_INCLUDED #include "main.h" int create_socket(void); void error_exit(char *message); void bind_socket(int *sock, unsigned long adress, unsigned short port); void cleanup(void); -int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client); -void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client); +int udp_recieve(int socket, unsigned char *data, int length, + struct sockaddr_in *client); +void udp_send(int socket, unsigned char *data, int length, + struct sockaddr_in *client); int mtime(void); #endif // CROSS_LAYER_H_INCLUDED diff --git a/include/functions.h b/include/functions.h index 39b0d01..1fdc6be 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,25 +1,31 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(int writesocket); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(unsigned char *message, int id); void PaketConfirmation(unsigned char *message, int id, int writesocket); int CheckPlayerData(unsigned char *password); unsigned char *GetEncodedString(unsigned char *string, int length); void CheckAllPlayerForReload(int writesocket); size_t u_strlen(unsigned char* buffer); -extern time_t firsttime; - #endif // FUNCTIONS_H_INCLUDED diff --git a/include/log.h b/include/log.h index cf3d22a..ea4b8f0 100644 --- a/include/log.h +++ b/include/log.h @@ -1,79 +1,86 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef LOG_H_INCLUDED #define LOG_H_INCLUDED #include "main.h" void myprintf(char *string, ...); void myprintf2(char *string, ...); /* -#define printf(...) file = fopen("log.txt","a+");\ + #define printf(...) file = fopen("log.txt","a+");\ time(&rawtime );\ timeinfo = localtime(&rawtime);\ fprintf(file, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ fprintf(file, __VA_ARGS__);\ printf("[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ printf(__VA_ARGS__);\ fclose(file) -#define eprintf(...) file = fopen("log.txt","a+");\ + #define eprintf(...) file = fopen("log.txt","a+");\ fprintf(file, __VA_ARGS__);\ fprintf(stdout, __VA_ARGS__);\ fclose(file) -extern FILE *file; + extern FILE *file; -extern time_t rawtime; -extern struct tm * timeinfo; -*/ + extern time_t rawtime; + extern struct tm * timeinfo; + */ #define printf(...) myprintf(__VA_ARGS__) #define eprintf(...) myprintf2(__VA_ARGS__) #endif // LOG_H_INCLUDED - /* - if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) - { - if((player[i].x - player[id].x) != 0 && (player[i].y - player[id].y) != 0) - { - float temprot = player[id].rotation; - double angle = atan2(player[i].x - player[id].x, player[i].y - player[id].y) * 180 / PI; - double angle2, angle3; - if(player[id].rotation < 0) - { - temprot += 180; - } - else if(player[id].rotation > 0) - { - temprot -= 180; - } - temprot = temprot *-1; - double victimangle = atan2(player[id].x - player[i].x, player[id].y - player[i].y) * 180 / PI; - double victimangle2 = victimangle + 90; - double victimangle3 = victimangle - 90; - int xPoint1, yPoint1; - int xPoint2, yPoint2; - xPoint1 = player[i].x + 16*cos(victimangle2*PI/180); - yPoint1 = player[i].y + 16*sin(victimangle2*PI/180); - xPoint2 = player[i].x + 16*cos(victimangle3*PI/180); - yPoint2 = player[i].y + 16*sin(victimangle3*PI/180); + if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) + { + if((player[i].x - player[id].x) != 0 && (player[i].y - player[id].y) != 0) + { + float temprot = player[id].rotation; + double angle = atan2(player[i].x - player[id].x, player[i].y - player[id].y) * 180 / PI; + double angle2, angle3; + if(player[id].rotation < 0) + { + temprot += 180; + } + else if(player[id].rotation > 0) + { + temprot -= 180; + } + temprot = temprot *-1; + double victimangle = atan2(player[id].x - player[i].x, player[id].y - player[i].y) * 180 / PI; + double victimangle2 = victimangle + 90; + double victimangle3 = victimangle - 90; + int xPoint1, yPoint1; + int xPoint2, yPoint2; + xPoint1 = player[i].x + 16*cos(victimangle2*PI/180); + yPoint1 = player[i].y + 16*sin(victimangle2*PI/180); + xPoint2 = player[i].x + 16*cos(victimangle3*PI/180); + yPoint2 = player[i].y + 16*sin(victimangle3*PI/180); - angle2 = atan2(xPoint1 - player[id].x, yPoint1 - player[id].y) * 180 / PI; - angle3 = atan2(xPoint2 - player[id].x, yPoint2 - player[id].y) * 180 / PI; - printf("(Debug2) %lf: %lf, %lf\n", temprot, angle2, angle3); + angle2 = atan2(xPoint1 - player[id].x, yPoint1 - player[id].y) * 180 / PI; + angle3 = atan2(xPoint2 - player[id].x, yPoint2 - player[id].y) * 180 / PI; + printf("(Debug2) %lf: %lf, %lf\n", temprot, angle2, angle3); - xP = xM + r*cos(ß) - yP = yM + r*sin(ß) + xP = xM + r*cos(ß) + yP = yM + r*sin(ß) - if((temprot <= angle2 && temprot >= angle3) || (temprot >= angle2 && temprot <= angle3)) - { - SendMessageToPlayer(id, "You hit someone!", 1, writesocket); - SendMessageToPlayer(i, "You were hitted by someone!", 1, writesocket); - OnHit(id, i, writesocket); - } - //SendMessageToPlayer(id, "Shooting not implemented yet!", 1, writesocket); - } + if((temprot <= angle2 && temprot >= angle3) || (temprot >= angle2 && temprot <= angle3)) + { + SendMessageToPlayer(id, "You hit someone!", 1, writesocket); + SendMessageToPlayer(i, "You were hitted by someone!", 1, writesocket); + OnHit(id, i, writesocket); + } + //SendMessageToPlayer(id, "Shooting not implemented yet!", 1, writesocket); + } - } - */ + } + */ diff --git a/include/main.h b/include/main.h index 963a0b4..24d671f 100644 --- a/include/main.h +++ b/include/main.h @@ -1,43 +1,51 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef MAIN_H_INCLUDED #define MAIN_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdarg.h> //log.h #include <math.h> //aim #define PI 3.14159265 #ifdef _WIN32 #include <winsock.h> #include <io.h> #else #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/select.h> //for select() #endif /* Self-made includes */ #include "log.h" #include "settings.h" #include "structs.h" #include "weapons.h" #include "cross_layer.h" #include "functions.h" #include "sendto_functions.h" #include "respond_messages.h" #include "pakets.h" #include "script-functions.h" #include "map.h" int main(); #endif // MAIN_H_INCLUDED diff --git a/include/map.h b/include/map.h index 36a456a..be19514 100644 --- a/include/map.h +++ b/include/map.h @@ -1,21 +1,28 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef MAP_H_INCLUDED #define MAP_H_INCLUDED #include "main.h" void ReadMap(); unsigned char *ReadLine(FILE *file); unsigned char ReadByte(FILE *file); int ReadInt(FILE *file); #define MAX_SPAWNPOINTS 10 unsigned short tspawnx[MAX_SPAWNPOINTS]; unsigned short tspawny[MAX_SPAWNPOINTS]; unsigned short tspawncount; unsigned short ctspawnx[MAX_SPAWNPOINTS]; unsigned short ctspawny[MAX_SPAWNPOINTS]; unsigned short ctspawncount; - #endif // MAP_H_INCLUDED diff --git a/include/pakets.h b/include/pakets.h index 90f302c..4ed289c 100644 --- a/include/pakets.h +++ b/include/pakets.h @@ -1,30 +1,50 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef PAKETS_H_INCLUDED #define PAKETS_H_INCLUDED #include "main.h" -int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position); -int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); -int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id); +int unknown(unsigned char *message, int length, unsigned char *buffer, + int size, int position); +int connection_setup_unknown(unsigned char *message, int length, + struct in_addr ip, unsigned short port); +int connection_setup_known(unsigned char *message, int length, + struct in_addr ip, unsigned short port, int id); int ping_ingame(unsigned char *message, int length, int id, int writesocket); -int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); -int confirmation_known(unsigned char *message, int length, int id, int writesocket); +int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, + unsigned short port); +int confirmation_known(unsigned char *message, int length, int id, + int writesocket); int fire(unsigned char *message, int length, int id, int writesocket); int advanced_fire(unsigned char *message, int length, int id, int writesocket); int buy(unsigned char *message, int length, int id, int writesocket); int rotupdate(unsigned char *message, int length, int id, int writesocket); int posupdatewalk(unsigned char *message, int length, int id, int writesocket); int posupdaterun(unsigned char *message, int length, int id, int writesocket); -int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket); -int posrotupdaterun(unsigned char *message, int length, int id, int writesocket); +int posrotupdatewalk(unsigned char *message, int length, int id, + int writesocket); +int + posrotupdaterun(unsigned char *message, int length, int id, + int writesocket); int respawnrequest(unsigned char *message, int length, int id, int writesocket); int weaponchange(unsigned char *message, int length, int id, int writesocket); int teamchange(unsigned char *message, int length, int id, int writesocket); -int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); -int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); -int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); +int ping_serverlist(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket); +int serverinfo_request(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket); +int joinroutine_unknown(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket); int specpos(unsigned char *message, int length, int id, int writesocket); int chatmessage(unsigned char *message, int length, int id, int writesocket); -int joinroutine_known(unsigned char *message, int length, int id, int writesocket); +int joinroutine_known(unsigned char *message, int length, int id, + int writesocket); int leave(int id, int writesocket); int reload(unsigned char *message, int length, int id, int writesocket); #endif // PAKETS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index 4377645..c352e75 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,24 +1,36 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" -void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); +void SendSpawnMessage(int id, unsigned short x, unsigned short y, + int writesocket); void SendAdvancedFireMessage(int id, int status, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); -void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); -void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); +void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, + int writesocket); +void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, + float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, char *message, int status, int writesocket); -void SendMessageToAll(unsigned char *message, int status, int writesocket); +void SendMessageToAll(char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); -void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); -void PingAllPlayer(int writesocket, time_t firsttime); +void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, + int writesocket); +void PingAllPlayer(int writesocket, time_t *firsttime); void SendReloadMessage(int id, int status, int writesocket); void SendPingList(int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/script-functions.h b/include/script-functions.h index 0c341dd..a68a047 100644 --- a/include/script-functions.h +++ b/include/script-functions.h @@ -1,24 +1,35 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef SCRIPT_H_INCLUDED #define SCRIPT_H_INCLUDED #include "main.h" int OnJoin(int id, int writesocket); int OnLeave(int id, int writesocket); int OnSpecmove(int id, int newx, int newy, int writesocket); int OnServerStart(); int OnExit(); int OnRespawnRequest(int id, int writesocket); int OnRespawn(int id, int writesocket); int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); int OnAdvancedFire(int id, int status, int writesocket); int OnFire(int id, int writesocket); int OnHit(int hitter, int victim, int writesocket); int OnBuyAttempt(int id, int wpnid, int writesocket); int OnBuy(int id, int wpnid, int writesocket); int OnKill(int hitter, int victim, int wpnid, int writesocket); int OnChatMessage(int id, unsigned char *message, int team, int writesocket); -int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket); -int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket); -int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket); +int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, + int writesocket); +int OnTeamChange(int id, unsigned char team, unsigned char skin, + int writesocket); +int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, + int writesocket); #endif diff --git a/include/sendto_functions.h b/include/sendto_functions.h index 6bd7edb..71242d3 100644 --- a/include/sendto_functions.h +++ b/include/sendto_functions.h @@ -1,17 +1,22 @@ /* - * sendto_functions.h + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file * - * Created on: 12.10.2010 - * Author: Jeremy + * Author/s of this file: Jermuk */ #ifndef SENDTO_FUNCTIONS_H_ #define SENDTO_FUNCTIONS_H_ #include "main.h" -void SendToPlayer(unsigned char *message, int length, int id, int reliable, int writesocket); -void SendToAll(unsigned char *message, int length, int reliable, int writesocket); -void SendToTeam(unsigned char *message, int length, int reliable, int team, int writesocket); -void SendToAllOther(int id, unsigned char *message, int length, int reliable, int writesocket); +void SendToPlayer(unsigned char *message, int length, int id, int reliable, + int writesocket); +void SendToAll(unsigned char *message, int length, int reliable, + int writesocket); +void SendToTeam(unsigned char *message, int length, int reliable, int team, + int writesocket); +void SendToAllOther(int id, unsigned char *message, int length, int reliable, + int writesocket); #endif /* SENDTO_FUNCTIONS_H_ */ diff --git a/include/settings.h b/include/settings.h index 2f8316f..87ce571 100644 --- a/include/settings.h +++ b/include/settings.h @@ -1,36 +1,44 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #define MAX_BUF 1024 /* --- Server Settings --- */ #define LOCAL_PORT 1994 #define MAX_CLIENTS 64 #define TIMEOUT 10 extern unsigned char pre_authcode[]; extern unsigned char sv_name[]; extern unsigned char sv_map[]; extern unsigned int sv_hostport; extern unsigned short sv_maxplayers; extern unsigned short sv_fow; extern unsigned short sv_gamemode; extern unsigned short sv_friendlyfire; extern unsigned short sv_usgnonly; extern unsigned char sv_password[]; extern unsigned short bot_count; extern unsigned short mp_roundtime; extern unsigned short mp_freezetime; extern unsigned short mp_c4timer; extern unsigned short mp_infammo; extern unsigned short mp_respawndelay; extern unsigned short mp_specmode; extern unsigned short onlineplayer; extern unsigned short mp_startmoney; #define STARTWEAPONS_COUNT 2 extern char startweapons[]; #endif // SETTINGS_H_INCLUDED diff --git a/include/structs.h b/include/structs.h index 4bdc09f..bc9fa17 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,88 +1,102 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" struct WEAPON { - short weapondamage, weapondamage_z1, weapondamage_z2; - short shoottime, reloadtime; - float freq; - short speed; - short slot; - short price; - short range; - short accuracy; - short ammo1, ammo2; - char *name; - short special; + short weapondamage, weapondamage_z1, weapondamage_z2; + short shoottime, reloadtime; + short freq; //every freq ms one shoot + short speed; + short slot; + short price; + short range; + short accuracy; + short ammo1, ammo2; + char *name; + short special; + short team; }; +/* + * team + * 0 - everyone can buy it + * 1 - t-only + * 2 - ct only + * 3 - unbuyable + */ struct PLAYER_WEAPON { - short id, slot; - short ammo1, ammo2; - short special; + short id, slot; + short ammo1, ammo2; + short special; }; /* * special * 0 = Normal * 1 = Silencer * 2 = Burst * 3 = Melee * 4 = 1xZoom * 5 = 2xZoom * 6 = Shotgun */ struct PLAYER { - int used; - unsigned short client_nummer; - unsigned short server_nummer; - time_t lastpaket; - unsigned short joinstatus; - - unsigned char *name; - unsigned char *spraylogo; - unsigned char *win; - unsigned short version; - unsigned short *usgn; - unsigned char team; - unsigned char skin; - unsigned short deaths; - short score; - unsigned short x,y; - unsigned char health, armor; - unsigned char actualweapon; - struct PLAYER_WEAPON slot[10]; - float rotation; //-180 to +180 - int specposx, specposy; - unsigned short money; - unsigned short kills; - int reloadtimer, reloading; + int used; + unsigned short client_nummer; + unsigned short server_nummer; + time_t lastpaket; + unsigned short joinstatus; - short dead; + unsigned char *name; + unsigned char *spraylogo; + unsigned char *win; + unsigned short version; + unsigned short *usgn; + unsigned char team; + unsigned char skin; + unsigned short deaths; + short score; + unsigned short x, y; + unsigned char health, armor; + unsigned char actualweapon; + struct PLAYER_WEAPON slot[10]; + float rotation; //-180 to +180 + int specposx, specposy; + unsigned short money; + unsigned short kills; + int reloadtimer, reloading; - int start; - unsigned short latency; + short dead; - int firetimer; - int zoommode; + int start; + unsigned short latency; + int firetimer, zoomtimer; + int zoommode; - /* Address*/ - unsigned short port; - struct in_addr ip; + /* Address*/ + unsigned short port; + struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; - struct TILE { - unsigned char mode; - unsigned char tileid; + unsigned char mode; + unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/include/weapons.h b/include/weapons.h index e6fc713..5804645 100644 --- a/include/weapons.h +++ b/include/weapons.h @@ -1,10 +1,21 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #ifndef WEAPONS_H_INCLUDED #define WEAPONS_H_INCLUDED #include "main.h" -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime, short special); +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, + short wpndmg_z2, short freq, short speed, short slot, short price, + short range, short accuracy, short ammo1, short ammo2, int reloadtime, + short special, short team); void WeaponInit(); struct WEAPON weapons[100]; #endif // WEAPONS_H_INCLUDED diff --git a/src/cross_layer.c b/src/cross_layer.c index 8be62e4..ccad392 100644 --- a/src/cross_layer.c +++ b/src/cross_layer.c @@ -1,191 +1,203 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/cross_layer.h" /** * \fn int create_socket(void) * \brief creates a socket * \return socketnumber or 0 if failed */ int create_socket(void) { #ifdef _WIN32 - WSADATA wsa; - if (WSAStartup (MAKEWORD(2,0), &wsa) != 0) - { - error_exit("WSAStartup() failed"); - } - else - { - int sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - { - error_exit("socket() failed"); - } - return sock; - } + WSADATA wsa; + if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) + { + error_exit("WSAStartup() failed"); + } + else + { + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + { + error_exit("socket() failed"); + } + return sock; + } #else - const int y = 1; - int sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - { - error_exit("socket() failed"); - } - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); - return sock; + const int y = 1; + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + { + error_exit("socket() failed"); + } + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); + return sock; #endif - return 0; + return 0; } /** * \fn int bind_socket(int *sock, unsigned long adress, unsigned short port) * \brief bind a socket to a specific IP and port * \param *sock socket to bind * \param adress ip-address to bind * \param port port to bind */ void bind_socket(int *sock, unsigned long adress, unsigned short port) { #ifdef _WIN32 - struct sockaddr_in server; - - memset(&server, 0, sizeof(server)); - server.sin_family = AF_INET; - server.sin_addr.s_addr = htonl(adress); - server.sin_port = htons(port); - if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) - { - error_exit("bind() failed"); - } + struct sockaddr_in server; + + memset(&server, 0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = htonl(adress); + server.sin_port = htons(port); + if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) + { + error_exit("bind() failed"); + } #else - struct sockaddr_in server; - memset(&server, 0, sizeof (server)); - server.sin_family = AF_INET; - server.sin_addr.s_addr = htonl(adress); - server.sin_port = htons(port); - if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) - { - error_exit("bind() failed"); - } + struct sockaddr_in server; + memset(&server, 0, sizeof (server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = htonl(adress); + server.sin_port = htons(port); + if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) + { + error_exit("bind() failed"); + } #endif } /** * \fn int error_exit(char *message) * \brief Show a error message and exit the programm * \param *message message to display */ void error_exit(char *message) { - printf("%s", message); - /* - printf("%s: %d\n", message, WSAGetLastError()); - //debug(stderr); - #else - printf("%s: %s\n", message, strerror(errno)); - //debug(stderr); - */ - - exit(EXIT_FAILURE); + printf("%s", message); + /* + printf("%s: %d\n", message, WSAGetLastError()); + //debug(stderr); + #else + printf("%s: %s\n", message, strerror(errno)); + //debug(stderr); + */ + + exit(EXIT_FAILURE); } /** * \fn cleanup(void) * \brief clean the socket */ void cleanup(void) { - OnExit(); + OnExit(); #ifdef _WIN32 - WSACleanup(); + WSACleanup(); #else - /* Nichts zu tun */ + /* Nichts zu tun */ #endif } /** * \fn mtime(void) * \brief return the actually time in miliseconds for win and linux * \return time in ms */ int mtime(void) { #ifdef _WIN32 return GetTickCount(); #else - struct timeval tv; - gettimeofday(&tv,NULL); - return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); + struct timeval tv; + gettimeofday(&tv,NULL); + return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); #endif } /** * \fn void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief send a message over a specific socket to a client * \param *socket socket to send over * \param *data data to send * \param length size of *data * \param *client sockaddr_in struct to send data to */ -void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) +void udp_send(int socket, unsigned char *data, int length, + struct sockaddr_in *client) { - int rc; - - //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); - rc = sendto(socket, (char*)data, length, 0, (struct sockaddr *)client, sizeof(*client)); - /* - int i; - for(i = 0; i <= length; i++) - { - printf("%d-", data[i]); - } - printf("\n"); - */ + int rc; + + //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); + rc = sendto(socket, (char*) data, length, 0, (struct sockaddr *) client, + sizeof(*client)); + /* + int i; + for(i = 0; i <= length; i++) + { + printf("%d-", data[i]); + } + printf("\n"); + */ #ifdef _WIN32 - if (rc == SOCKET_ERROR) - error_exit("sendto() failed"); + if (rc == SOCKET_ERROR) + error_exit("sendto() failed"); #else - if (rc < 0) - error_exit("sendto() failed"); + if (rc < 0) + error_exit("sendto() failed"); #endif - //else - //printf("Message sent!\n"); + //else + //printf("Message sent!\n"); } /** * \fn int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief Recieves a message on a specicific socket and save (if something recieved) the data * \param socket socket to recieve * \param *data pointer where the data should be saved * \param length max length of *data * \param *client pointer where the clientdata (ip, ...) should be saved * \return length of read data */ -int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) +int udp_recieve(int socket, unsigned char *data, int length, + struct sockaddr_in *client) { - struct sockaddr_in newclient; - int len; - int size; - len = sizeof(struct sockaddr_in); - size = recvfrom(socket, (char*)data, length, 0, (struct sockaddr *)&newclient,&len); - *client = newclient; + struct sockaddr_in newclient; + int len; + int size; + len = sizeof(struct sockaddr_in); + size = recvfrom(socket, (char*) data, length, 0, + (struct sockaddr *) &newclient, &len); + *client = newclient; #ifdef _WIN32 - if (size == SOCKET_ERROR) - { - error_exit("recvfrom() failed"); - } + if (size == SOCKET_ERROR) + { + error_exit("recvfrom() failed"); + } #else - if (size < 0) - { - error_exit("recvfrom() failed"); - } + if (size < 0) + { + error_exit("recvfrom() failed"); + } #endif - else - { - return size; - } - return 0; + else + { + return size; + } + return 0; } diff --git a/src/functions.c b/src/functions.c index 8c77461..551581d 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,421 +1,438 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) - { - return i; - } - } - return -1; + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (!strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port + == player[i].port) + { + return i; + } + } + return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { - player[id].used = 0; - player[id].client_nummer = 0; - player[id].server_nummer = 0; - player[id].lastpaket = 0; - player[id].joinstatus = 0; + player[id].used = 0; + player[id].client_nummer = 0; + player[id].server_nummer = 0; + player[id].lastpaket = 0; + player[id].joinstatus = 0; - free(player[id].name); - player[id].name = NULL; - free(player[id].spraylogo); - player[id].spraylogo = NULL; - free(player[id].win); - player[id].win = NULL; - free(player[id].usgn); - player[id].usgn = NULL; - player[id].version = 0; + free(player[id].name); + player[id].name = NULL; + free(player[id].spraylogo); + player[id].spraylogo = NULL; + free(player[id].win); + player[id].win = NULL; + free(player[id].usgn); + player[id].usgn = NULL; + player[id].version = 0; - player[id].team = 0; - player[id].deaths = 0; - player[id].score = 0; + player[id].team = 0; + player[id].deaths = 0; + player[id].score = 0; - player[id].x = 0; - player[id].y = 0; + player[id].x = 0; + player[id].y = 0; - player[id].health = 0; - player[id].armor = 0; + player[id].health = 0; + player[id].armor = 0; - player[id].actualweapon = 0; - player[id].reloading = 0; - player[id].reloadtimer = 0; + player[id].actualweapon = 0; + player[id].reloading = 0; + player[id].reloadtimer = 0; + player[id].zoomtimer = 0; + player[id].firetimer = 0; - int i; - for(i = 0; i <= 9; i++) - { - player[id].slot[i].id = 0; - } - player[id].rotation = 0; + int i; + for (i = 0; i <= 9; i++) + { + player[id].slot[i].id = 0; + } + player[id].rotation = 0; - player[id].dead = 1; + player[id].dead = 1; - player[id].start = 0; - player[id].money = mp_startmoney; - player[id].zoommode = 0; + player[id].start = 0; + player[id].money = mp_startmoney; + player[id].zoommode = 0; - /* Address*/ - player[id].port = 0; - //player[id].ip = ""; + /* Address*/ + player[id].port = 0; + //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - ClearPlayer(i); - } + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + ClearPlayer(i); + } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if (player[i].used == 1 && PlayerTimeout(i)) - { - printf("Client %d timed out!\n", i); - SendLeaveMessage(i, writesocket); - ClearPlayer(i); - } - } + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && PlayerTimeout(i)) + { + printf("Client %d timed out!\n", i); + SendLeaveMessage(i, writesocket); + ClearPlayer(i); + } + } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { - int i; - for(i = 0; i <= 9; i++) - { - if(player[id].slot[i].id == 0) - { - player[id].slot[i].id = wpnid; - player[id].slot[i].slot = weapons[wpnid].slot; - player[id].slot[i].ammo1 = weapons[wpnid].ammo1; - player[id].slot[i].ammo2 = weapons[wpnid].ammo2; - return i; - } - } - return 0; + int i; + for (i = 0; i <= 9; i++) + { + if (player[id].slot[i].id == 0) + { + player[id].slot[i].id = wpnid; + player[id].slot[i].slot = weapons[wpnid].slot; + player[id].slot[i].ammo1 = weapons[wpnid].ammo1; + player[id].slot[i].ammo2 = weapons[wpnid].ammo2; + return i; + } + } + return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { - int i; - for(i = 0; i <= 9; i++) - { - if(player[id].slot[i].id == wpnid) - { - player[id].slot[i].id = 0; - player[id].slot[i].slot = 0; - player[id].slot[i].ammo1 = 0; - player[id].slot[i].ammo2 = 0; - break; - } - } + int i; + for (i = 0; i <= 9; i++) + { + if (player[id].slot[i].id == wpnid) + { + player[id].slot[i].id = 0; + player[id].slot[i].slot = 0; + player[id].slot[i].ammo1 = 0; + player[id].slot[i].ammo2 = 0; + break; + } + } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { - int i; - for(i = 0; i <= 9; i++) - { - player[id].slot[i].id = 0; - player[id].slot[i].slot = 0; - player[id].slot[i].ammo1 = 0; - player[id].slot[i].ammo2 = 0; - } + int i; + for (i = 0; i <= 9; i++) + { + player[id].slot[i].id = 0; + player[id].slot[i].slot = 0; + player[id].slot[i].ammo1 = 0; + player[id].slot[i].ammo2 = 0; + player[id].slot[i].special = 0; + player[id].zoommode = 0; + + } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * */ int PlayerTimeout(int id) { - //id = 0; + //id = 0; - time_t actualtime; - time(&actualtime); + time_t actualtime; + time(&actualtime); - if(((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket != 0) - { - return 1; - } - return 0; + if (((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket + != 0) + { + return 1; + } + return 0; } - /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { - unsigned short serverstatus = 0; - if(strcmp((char*)sv_password, "")) - { - serverstatus += 1; - } - if(sv_usgnonly == 1) - { - serverstatus += 2; - } - if(sv_fow == 1) - { - serverstatus += 4; - } - if(sv_friendlyfire == 1) - { - serverstatus += 8; - } - if(1) //Same Version? - { - serverstatus += 16; - } - if(sv_gamemode != 0) - { - serverstatus += 32; - } - if(0) //LuaScripts - { - serverstatus += 64; - } - if(1) //Dedicated - { - serverstatus += 128; - } - return serverstatus; + unsigned short serverstatus = 0; + if (strcmp((char*) sv_password, "")) + { + serverstatus += 1; + } + if (sv_usgnonly == 1) + { + serverstatus += 2; + } + if (sv_fow == 1) + { + serverstatus += 4; + } + if (sv_friendlyfire == 1) + { + serverstatus += 8; + } + if (1) //Same Version? + { + serverstatus += 16; + } + if (sv_gamemode != 0) + { + serverstatus += 32; + } + if (0) //LuaScripts + { + serverstatus += 64; + } + if (1) //Dedicated + { + serverstatus += 128; + } + return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { - *x = (*x>>8) | - (*x<<8); - return *x; + *x = (*x >> 8) | (*x << 8); + return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { - *x = (*x>>24) | - ((*x<<8) & 0x00FF0000) | - ((*x>>8) & 0x0000FF00) | - (*x<<24); - return *x; + *x = (*x >> 24) | ((*x << 8) & 0x00FF0000) | ((*x >> 8) & 0x0000FF00) | (*x + << 24); + return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(unsigned char *message, int id) { - unsigned short *pTempNummer = malloc(sizeof(unsigned short)); - pTempNummer[0] = message[0]; - pTempNummer[1] = message[1]; - if(*pTempNummer % 2 != 0) - { - if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) - { - printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); - free(pTempNummer); - return 0; - } - } - if(*pTempNummer-1 > player[id].client_nummer) - { - player[id].client_nummer = *pTempNummer; - } - /* - unsigned short *pNummer = &player[id].client_nummer; - pNummer[0] = buffer[0]; - pNummer[1] = buffer[1]; - */ - free(pTempNummer); - return 1; + unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + if (*pTempNummer % 2 != 0) + { + if (((*pTempNummer) + 2) < player[id].client_nummer || (*pTempNummer) + > (player[id].client_nummer + 2)) + { + printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); + free(pTempNummer); + return 0; + } + } + if (*pTempNummer - 1 > player[id].client_nummer) + { + player[id].client_nummer = *pTempNummer; + } + /* + unsigned short *pNummer = &player[id].client_nummer; + pNummer[0] = buffer[0]; + pNummer[1] = buffer[1]; + */ + free(pTempNummer); + return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(unsigned char *message, int id, int writesocket) { - unsigned short *pTempNummer = malloc(sizeof(unsigned short)); - pTempNummer[0] = message[0]; - pTempNummer[1] = message[1]; - if(*pTempNummer % 2 == 0) - { - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - buffer[0] = 0x01; - memcpy(buffer+1, pTempNummer, 2); + unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + if (*pTempNummer % 2 == 0) + { + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + buffer[0] = 0x01; + memcpy(buffer + 1, pTempNummer, 2); - SendToPlayer(buffer, stringsize, id, 0, writesocket); + SendToPlayer(buffer, stringsize, id, 0, writesocket); - free(buffer); - } - free(pTempNummer); + free(buffer); + } + free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(unsigned char *password) { - if( strcmp((char*)sv_password, (char*)password) != 0 ) - { - printf("Password wrong!\n"); - return 1; - } - if(sv_maxplayers == onlineplayer) - { - printf("Server full!\n"); - return 3; - } - /* - 0 - Normal - 1 - Password wrong - 2 - USGN only - 3 - Server full - 4 - Banned - 5 - Another Game Version - 6 - ?? - 7 - Can't validate user (USGN offline) - 8 - ?? - 9 - Connection already exists - 10 - Wrong client (pre_authcode) - 11 - Different map (temp, etc.) - 12 - Map unknown (maptransfer disabled) - 13++ - Failed to join - */ + if (strcmp((char*) sv_password, (char*) password) != 0) + { + printf("Password wrong!\n"); + return 1; + } + if (sv_maxplayers == onlineplayer) + { + printf("Server full!\n"); + return 3; + } + /* + 0 - Normal + 1 - Password wrong + 2 - USGN only + 3 - Server full + 4 - Banned + 5 - Another Game Version + 6 - ?? + 7 - Can't validate user (USGN offline) + 8 - ?? + 9 - Connection already exists + 10 - Wrong client (pre_authcode) + 11 - Different map (temp, etc.) + 12 - Map unknown (maptransfer disabled) + 13++ - Failed to join + */ - return 0; + return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { - unsigned char *buffer = malloc(length+1); //+1 need for \0 - if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); + unsigned char *buffer = malloc(length + 1); //+1 need for \0 + if (buffer == NULL) + error_exit("Memory error ( GetEncodedString() )\n"); - int i; - for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) - { - if ((i % 3) == 0) - { - buffer[i] = string[i] + 110; - } - else if ((i % 3) == 1) - { - buffer[i] = string[i] + 97; - } - else if ((i % 3) == 2) - { - buffer[i] = string[i] + 109; - } - } - buffer[length] = '\0'; + int i; + for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) + { + if ((i % 3) == 0) + { + buffer[i] = string[i] + 110; + } + else if ((i % 3) == 1) + { + buffer[i] = string[i] + 97; + } + else if ((i % 3) == 2) + { + buffer[i] = string[i] + 109; + } + } + buffer[length] = '\0'; - return buffer; + return buffer; } /** * \fn void CheckAllPlayerForReload(int writesocket) * \brief check all player if their reload is ended, * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; - for(i = 1; i <= sv_maxplayers; i++) + for (i = 1; i <= sv_maxplayers; i++) { - if(player[i].reloading != 0) + if (player[i].reloading != 0) { - if(player[i].reloadtimer <= mtime()) + if (player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); - if(player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) + if (player[i].slot[player[i].reloading].ammo2 + -= player[i].slot[player[i].reloading].ammo1 > 0) { - player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; - player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; + player[i].slot[player[i].reloading].ammo2 + -= player[i].slot[player[i].reloading].ammo1; + player[i].slot[player[i].reloading].ammo1 + = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { - player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; + player[i].slot[player[i].reloading].ammo1 + = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } size_t u_strlen(unsigned char* buffer) { - return strlen((char*)buffer); + return strlen((char*) buffer); } diff --git a/src/log.c b/src/log.c index 049ecbd..94bba26 100644 --- a/src/log.c +++ b/src/log.c @@ -1,81 +1,90 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/log.h" /** * \fn void myprintf(char *string, ...) * \brief prints string with time to stdout and logfile * \param *string the string to print out (same syntax as printf) * \param ... the other parameters, if necessary */ void myprintf(char *string, ...) { #ifdef _WIN32 - FILE *logfile; - time_t rawtime; - struct tm * timeinfo; + FILE *logfile; + time_t rawtime; + struct tm * timeinfo; - logfile = fopen("log.txt","a+"); - if(logfile != NULL) - { - time(&rawtime); - timeinfo = localtime(&rawtime); - //fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); - fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + logfile = fopen("log.txt", "a+"); + if (logfile != NULL) + { + time(&rawtime); + timeinfo = localtime(&rawtime); + //fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, + timeinfo->tm_sec); - va_list argzeiger; - va_start(argzeiger,string); - vprintf(string,argzeiger); - //vfprintf(logfile, string, argzeiger); - va_end(argzeiger); + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string, argzeiger); + //vfprintf(logfile, string, argzeiger); + va_end(argzeiger); - fclose(logfile); - } - else - { - printf("Cannot open logfile!\n"); - } + fclose(logfile); + } + else + { + printf("Cannot open logfile!\n"); + } #else - time_t rawtime; - struct tm * timeinfo; - time(&rawtime); - timeinfo = localtime(&rawtime); - fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + time_t rawtime; + struct tm * timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); - va_list argzeiger; - va_start(argzeiger,string); - vprintf(string,argzeiger); - va_end(argzeiger); + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string,argzeiger); + va_end(argzeiger); #endif } /** * \fn void myprintf2(char *string, ...) * \brief same as myprintf, just with the difference, that the time won't be printed * \param *string the string to print out (same syntax as printf) * \param ... the other parameters, if necessary */ void myprintf2(char *string, ...) { #ifdef _WIN32 - FILE *logfile; - logfile = fopen("log.txt","a+"); - if(logfile != NULL) - { - va_list argzeiger; - va_start(argzeiger,string); - vprintf(string,argzeiger); - vfprintf(logfile, string, argzeiger); - va_end(argzeiger); + FILE *logfile; + logfile = fopen("log.txt", "a+"); + if (logfile != NULL) + { + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string, argzeiger); + vfprintf(logfile, string, argzeiger); + va_end(argzeiger); - fclose(logfile); - } - else - { - printf("Cannot open logfile!\n"); - } + fclose(logfile); + } + else + { + printf("Cannot open logfile!\n"); + } #else - va_list argzeiger; - va_start(argzeiger,string); - vprintf(string,argzeiger); - va_end(argzeiger); + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string,argzeiger); + va_end(argzeiger); #endif } diff --git a/src/main.c b/src/main.c index cda2985..2cbe81e 100644 --- a/src/main.c +++ b/src/main.c @@ -1,254 +1,253 @@ /* - * Published under GPL v3 - * Copyright by DÖNARMASTER aka Jermuk and <www.Kebab-Clan.de> + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file * - * Alpha 0.1 - * - * If you want to help me or you have questions - * contact me via PM (Jermuk) or E-Mail <[email protected]> + * Author/s of this file: Jermuk */ #include "../include/main.h" - /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); /** * \var needed for PingAllPlayer() to execute it every 5 sec - */ + */ time_t firsttime; time(&firsttime); while (1) { CheckForTimeout(readsocket); - PingAllPlayer(readsocket, firsttime); /// also execute PingList() + PingAllPlayer(readsocket, &firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); select(readsocket + 1, &descriptor, NULL, NULL, NULL); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 8: - rtn = advanced_fire(message, tempsize, id, readsocket); + rtn = advanced_fire(message, tempsize, id, + readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: - rtn = specpos(message, tempsize, id, + rtn + = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) - */ + */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) - */ + */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return EXIT_SUCCESS; } diff --git a/src/map.c b/src/map.c index 1fcb516..a152c7a 100644 --- a/src/map.c +++ b/src/map.c @@ -1,206 +1,219 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/map.h" /** * \fn void ReadMap() * \brief reads the map and put all needed information into a variable * needed: tspawn and ctspawn */ void ReadMap() { FILE *file; int i; tspawncount = 0; ctspawncount = 0; char *mappath = malloc(u_strlen(sv_map) + 5); memcpy(mappath, sv_map, u_strlen(sv_map)); memcpy(mappath + u_strlen(sv_map), ".map\0", 5); file = fopen(mappath, "rb"); if (file == NULL) error_exit("Map not found.. Abort\n"); - else printf("Loading '%s'..", mappath); + else printf("Loading '%s'..", mappath); free(mappath); //------------------------------ unsigned char *mapheader = ReadLine(file); for (i = 1; i <= 9; i++) ReadByte(file); for (i = 1; i <= 10; i++) ReadInt(file); for (i = 1; i <= 10; i++) ReadLine(file); unsigned char *code = ReadLine(file); unsigned char *tileset = ReadLine(file); unsigned char loaded = ReadByte(file); int maxx = ReadInt(file); int maxy = ReadInt(file); unsigned char *background = ReadLine(file); - /*int backgroundx =*/ ReadInt(file); //avoid warnings: unused variable - /*int backgroundy =*/ ReadInt(file); - /*unsigned char red =*/ ReadByte(file); - /*unsigned char green =*/ ReadByte(file); - /*unsigned char blue =*/ ReadByte(file); + /*int backgroundx =*/ + ReadInt(file); //avoid warnings: unused variable + /*int backgroundy =*/ + ReadInt(file); + /*unsigned char red =*/ + ReadByte(file); + /*unsigned char green =*/ + ReadByte(file); + /*unsigned char blue =*/ + ReadByte(file); unsigned char *mapcheck = ReadLine(file); //----------------------------------------- unsigned char *tilemode = malloc(loaded + 1); if (tilemode == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= loaded; i++) { tilemode[i] = ReadByte(file); } map = malloc(maxx * sizeof(struct TILE *)); if (map == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= maxx; i++) { map[i] = malloc(maxy * sizeof(struct TILE *)); if (map[i] == NULL) error_exit("Memory error in ReadMap()\n"); int b; for (b = 0; b <= maxy; b++) { unsigned char bytecache = ReadByte(file); if (bytecache > loaded) { bytecache = 0; } map[i][b].tileid = bytecache; map[i][b].mode = tilemode[bytecache]; //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); } } //--------------------------------------- unsigned char enities_count = ReadByte(file); for (i = 0; i <= enities_count - 1; i++) { unsigned char *name = ReadLine(file); unsigned char typ = ReadByte(file); int x = ReadInt(file); int y = ReadInt(file); unsigned char *trigger = ReadLine(file); //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); int b; for (b = 0; b <= 9; b++) { - /*int unknownint =*/ ReadInt(file); + /*int unknownint =*/ReadInt(file); unsigned char *unknown = ReadLine(file); //eprintf("(%d) %s || ", unknownint, unknown); free(unknown); } switch (typ) { case 0: { tspawnx[tspawncount] = x; tspawny[tspawncount] = y; tspawncount++; break; } case 1: { ctspawnx[ctspawncount] = x; ctspawny[ctspawncount] = y; ctspawncount++; break; } default: { break; } } free(name); free(trigger); } fclose(file); eprintf("loaded!\n"); free(mapheader); free(code); free(tileset); free(background); free(mapcheck); } /** * \fn unsigned char *ReadLine(FILE *file) * \brief read from a file stream a cs2d line (ends with \r\n; windows end) * \param *file the file stream * \return a pointer to the read line */ unsigned char *ReadLine(FILE *file) { int position = 0; char *line = NULL; char c; while ((c = fgetc(file)) != 13) { if (c == EOF) error_exit("EndOfFile in ReadByte()\n"); line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = c; position++; } line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = '\0'; position++; fgetc(file); //0x0A - return (unsigned char*)line; + return (unsigned char*) line; } /** * \fn unsigned char ReadByte(FILE *file) * \brief read from a file stream a byte * \param *file the file stream * \return the read byte */ unsigned char ReadByte(FILE *file) { unsigned char byte = fgetc(file); if (byte == EOF) error_exit("EndOfFile in ReadByte()\n"); return byte; } /** * \fn int ReadInt(FILE *file) * \brief read from a file stream a integer * \param *file the file stream * \return the read integer */ int ReadInt(FILE *file) { unsigned char byte1 = fgetc(file); if (byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte2 = fgetc(file); if (byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte3 = fgetc(file); if (byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte4 = fgetc(file); if (byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/pakets.c b/src/pakets.c index 8407716..9415ed3 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -1,1651 +1,1707 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/pakets.h" /** * \fn int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) * \brief every unknown packet lands here * \param *message pointer to the unknown message * \param length sizeof message * \param *buffer pointer to the udp-packet * \param size sizeof buffer * \param position where the unknown message in buffer begins * \return read bytes (specific: parameter length) */ -int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) +int unknown(unsigned char *message, int length, unsigned char *buffer, + int size, int position) { - int paketlength = length; - int i; - printf("Unknown packet: "); - for(i = 2; i <= position-1; i++) - { - eprintf("%d-", buffer[i]); - } - eprintf("\n\t"); - for(i = 0; i <= length-1; i++) - { - eprintf("%d-", message[i]); - } - eprintf("\n"); - return paketlength; + int paketlength = length; + int i; + printf("Unknown packet: "); + for (i = 2; i <= position - 1; i++) + { + eprintf("%d-", buffer[i]); + } + eprintf("\n\t"); + for (i = 0; i <= length - 1; i++) + { + eprintf("%d-", message[i]); + } + eprintf("\n"); + return paketlength; } /** * \fn int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a connection setup for unknown player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ -int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) +int connection_setup_unknown(unsigned char *message, int length, + struct in_addr ip, unsigned short port) { - int paketlength = 3; - if(length < paketlength) - { - printf("Invalid packet (connection_setup_unknown)!\n"); - return length; - } - return paketlength; + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (connection_setup_unknown)!\n"); + return length; + } + return paketlength; } /** * \fn int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a connection setup for known player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ -int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id) +int connection_setup_known(unsigned char *message, int length, + struct in_addr ip, unsigned short port, int id) { - int paketlength = 3; - if(length < paketlength) - { - printf("Invalid packet (connection_setup_known)!\n"); - return length; - } - - return paketlength; + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (connection_setup_known)!\n"); + return length; + } + + return paketlength; } /** * \fn int ping_ingame(unsigned char *message, int length, int id, int writesocket) * \brief handles a answer from the server ingame ping. this function calculates the latency * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_ingame(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 5; - if(length < paketlength) - { - printf("Invalid packet (ping_ingame)!\n"); - return length; - } - player[id].latency = mtime() - player[id].start; - //printf("%s: %d\n", player[id].name, player[id].latency); - return paketlength; + int paketlength = 5; + if (length < paketlength) + { + printf("Invalid packet (ping_ingame)!\n"); + return length; + } + player[id].latency = mtime() - player[id].start; + //printf("%s: %d\n", player[id].name, player[id].latency); + return paketlength; } /** * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a confirmation for unknown player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ -int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) +int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, + unsigned short port) { - int paketlength = 3; - if(length < paketlength) - { - printf("Invalid packet (confirmation_unknown)!\n"); - return length; - } - - return paketlength; + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (confirmation_unknown)!\n"); + return length; + } + + return paketlength; } /** * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) * \brief handles a confirmation for known player * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ -int confirmation_known(unsigned char *message, int length, int id, int writesocket) +int confirmation_known(unsigned char *message, int length, int id, + int writesocket) { - int paketlength = 3; - if(length < paketlength) - { - printf("Invalid packet (confirmation_known)!\n"); - return length; - } - return paketlength; + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (confirmation_known)!\n"); + return length; + } + return paketlength; } /** * \fn int fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a fire * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int fire(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 1; - if(length < paketlength) - { - printf("Invalid packet (fire)!\n"); - return length; - } - switch(OnFire(id, writesocket)) - { - case 0: - SendFireMessage(id, writesocket); - break; - case 1: - break; - } - return paketlength; + int paketlength = 1; + if (length < paketlength) + { + printf("Invalid packet (fire)!\n"); + return length; + } + switch (OnFire(id, writesocket)) + { + case 0: + SendFireMessage(id, writesocket); + break; + case 1: + break; + } + return paketlength; } /** * \fn int advanced_fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a advanced_fire (right click) * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int advanced_fire(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 2; - if(length < paketlength) - { - printf("Invalid packet (advanced_fire)!\n"); - return length; - } - unsigned int status = message[1]; - - switch(OnAdvancedFire(id, status, writesocket)) - { - case 0: - SendAdvancedFireMessage(id, status, writesocket); - break; - case 1: - break; - } - return paketlength; + int paketlength = 2; + if (length < paketlength) + { + printf("Invalid packet (advanced_fire)!\n"); + return length; + } + unsigned int status = message[1]; + + switch (OnAdvancedFire(id, status, writesocket)) + { + case 0: + SendAdvancedFireMessage(id, status, writesocket); + break; + case 1: + break; + } + return paketlength; } /** * \fn int buy(unsigned char *message, int length, int id, int writesocket) * \brief handles a buy request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int buy(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 3; - if(length < paketlength) - { - printf("Invalid packet (buy)!\n"); - return length; - } - - int position = 1; - int wpnid; - - wpnid = message[position]; - position++; - - switch(OnBuyAttempt(id, wpnid, writesocket)) - { - case 0: - OnBuy(id, wpnid, writesocket); - SendBuyMessage(id, wpnid, writesocket); - break; - case 1: - break; - } - return paketlength; + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (buy)!\n"); + return length; + } + + int position = 1; + int wpnid; + + wpnid = message[position]; + position++; + + switch (OnBuyAttempt(id, wpnid, writesocket)) + { + case 0: + OnBuy(id, wpnid, writesocket); + SendBuyMessage(id, wpnid, writesocket); + break; + case 1: + break; + } + return paketlength; } /** * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) * \brief handles a rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int rotupdate(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 5; - float temprotation; - if(length < paketlength) - { - printf("Invalid packet (rot_update)!\n"); - return length; - } - memcpy(&temprotation, message+1, sizeof(float)); - if(temprotation >= -180 && temprotation <= 180) - { - //if(temprotation < 0) temprotation += 360; - memcpy(&player[id].rotation, &temprotation, sizeof(float)); - SendRotUpdate(id, player[id].rotation, writesocket); - } - return paketlength; + int paketlength = 5; + float temprotation; + if (length < paketlength) + { + printf("Invalid packet (rot_update)!\n"); + return length; + } + memcpy(&temprotation, message + 1, sizeof(float)); + if (temprotation >= -180 && temprotation <= 180) + { + //if(temprotation < 0) temprotation += 360; + memcpy(&player[id].rotation, &temprotation, sizeof(float)); + SendRotUpdate(id, player[id].rotation, writesocket); + } + return paketlength; } /** * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) * \brief handles a position walk update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 5; - unsigned short tempx; - unsigned short tempy; - if(length < paketlength) - { - printf("Invalid packet (posupdatewalk)!\n"); - return length; - } - memcpy(&tempx, message+1, 2); - memcpy(&tempy, message+3, 2); - switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) - { - case 0: - SendPosUpdate(id, tempx, tempy, 0, writesocket); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); - break; - default: - break; - } - return paketlength; + int paketlength = 5; + unsigned short tempx; + unsigned short tempy; + if (length < paketlength) + { + printf("Invalid packet (posupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + SendPosUpdate(id, tempx, tempy, 0, writesocket); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); + break; + default: + break; + } + return paketlength; } /** * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) * \brief handles a position run update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdaterun(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 5; - unsigned short tempx; - unsigned short tempy; - if(length < paketlength) - { - printf("Invalid packet (posupdaterun)!\n"); - return length; - } - memcpy(&tempx, message+1, 2); - memcpy(&tempy, message+3, 2); - switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) - { - case 0: - SendPosUpdate(id, tempx, tempy, 1, writesocket); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); - break; - default: - break; - } - return paketlength; + int paketlength = 5; + unsigned short tempx; + unsigned short tempy; + if (length < paketlength) + { + printf("Invalid packet (posupdaterun)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + SendPosUpdate(id, tempx, tempy, 1, writesocket); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); + break; + default: + break; + } + return paketlength; } /** * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position walk and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ -int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) +int posrotupdatewalk(unsigned char *message, int length, int id, + int writesocket) { - int paketlength = 9; - unsigned short tempx; - unsigned short tempy; - float rotation; - if(length < paketlength) - { - printf("Invalid packet (posrotupdatewalk)!\n"); - return length; - } - memcpy(&tempx, message+1, 2); - memcpy(&tempy, message+3, 2); - memcpy(&rotation, message+5, sizeof(float)); - - if(rotation >= -180 && rotation <= 180) - { - switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) - { - case 0: - //if(rotation < 0) rotation += 360; - SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); - memcpy(&player[id].rotation, &rotation, sizeof(float)); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); - break; - default: - break; - } - } - return paketlength; + int paketlength = 9; + unsigned short tempx; + unsigned short tempy; + float rotation; + if (length < paketlength) + { + printf("Invalid packet (posrotupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + memcpy(&rotation, message + 5, sizeof(float)); + + if (rotation >= -180 && rotation <= 180) + { + switch (OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + //if(rotation < 0) rotation += 360; + SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); + memcpy(&player[id].rotation, &rotation, sizeof(float)); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosRotUpdate(id, player[id].x, player[id].y, 0, + player[id].rotation, writesocket); + break; + default: + break; + } + } + return paketlength; } /** * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position run and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 9; - unsigned short tempx; - unsigned short tempy; - float rotation; - if(length < paketlength) - { - printf("Invalid packet (posrotupdatewalk)!\n"); - return length; - } - memcpy(&tempx, message+1, 2); - memcpy(&tempy, message+3, 2); - memcpy(&rotation, message+5, sizeof(float)); - - if(rotation >= -180 && rotation <= 180) - { - switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) - { - case 0: - //if(rotation < 0) rotation += 360; - SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); - memcpy(&player[id].rotation, &rotation, sizeof(float)); - player[id].x = tempx; - player[id].y = tempy; - break; - case 1: - SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); - break; - default: - break; - } - } - return paketlength; + int paketlength = 9; + unsigned short tempx; + unsigned short tempy; + float rotation; + if (length < paketlength) + { + printf("Invalid packet (posrotupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message + 1, 2); + memcpy(&tempy, message + 3, 2); + memcpy(&rotation, message + 5, sizeof(float)); + + if (rotation >= -180 && rotation <= 180) + { + switch (OnMoveAttempt(id, tempx, tempy, 1, writesocket)) + { + case 0: + //if(rotation < 0) rotation += 360; + SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); + memcpy(&player[id].rotation, &rotation, sizeof(float)); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosRotUpdate(id, player[id].x, player[id].y, 1, + player[id].rotation, writesocket); + break; + default: + break; + } + } + return paketlength; } /** * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) * \brief handles a respawn request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int respawnrequest(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 1; - if(length < paketlength) - { - printf("Invalid packet (respawnrequest)! (WTF?)\n"); - return length; - } - switch(OnRespawnRequest(id, writesocket)) - { - case 0: - srand(time(NULL)); - switch(player[id].team) - { - case 0: - printf("%s tried to spawn as spectator!\n", player[id].name); - break; - case 1: - { - int tmp = rand() % tspawncount; - printf("%s spawned!\n", player[id].name); - player[id].health = 100; - player[id].dead = 0; - player[id].x = (tspawnx[tmp]+0.5)*32; - player[id].y = (tspawny[tmp]+0.5)*32; - SendSpawnMessage(id, player[id].x, player[id].y, writesocket); - break; - } - case 2: - { - int tmp = rand() % ctspawncount; - printf("%s spawned!\n", player[id].name); - player[id].health = 100; - player[id].dead = 0; - player[id].x = (ctspawnx[tmp]+0.5)*32; - player[id].y = (ctspawny[tmp]+0.5)*32; - SendSpawnMessage(id, player[id].x, player[id].y, writesocket); - break; - } - - } - break; - case 1: - break; - default: - break; - } - return paketlength; + int paketlength = 1; + if (length < paketlength) + { + printf("Invalid packet (respawnrequest)! (WTF?)\n"); + return length; + } + switch (OnRespawnRequest(id, writesocket)) + { + case 0: + srand(time(NULL)); + switch (player[id].team) + { + case 0: + printf("%s tried to spawn as spectator!\n", player[id].name); + break; + case 1: + { + int tmp = rand() % tspawncount; + printf("%s spawned!\n", player[id].name); + player[id].health = 100; + player[id].dead = 0; + player[id].x = (tspawnx[tmp] + 0.5) * 32; + player[id].y = (tspawny[tmp] + 0.5) * 32; + SendSpawnMessage(id, player[id].x, player[id].y, writesocket); + break; + } + case 2: + { + int tmp = rand() % ctspawncount; + printf("%s spawned!\n", player[id].name); + player[id].health = 100; + player[id].dead = 0; + player[id].x = (ctspawnx[tmp] + 0.5) * 32; + player[id].y = (ctspawny[tmp] + 0.5) * 32; + SendSpawnMessage(id, player[id].x, player[id].y, writesocket); + break; + } + + } + break; + case 1: + break; + default: + break; + } + return paketlength; } /** * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a weapon change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int weaponchange(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 3; - if(length < paketlength) - { - printf("Invalid packet (weaponchange)!\n"); - return length; - } - int position = 1; - int wpnid; - - wpnid = message[position]; - position++; - - switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) - { - case 0: - SendWeaponChangeMessage(id, wpnid, writesocket); - break; - case 1: - break; - default: - break; - } - return paketlength; + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (weaponchange)!\n"); + return length; + } + int position = 1; + int wpnid; + + wpnid = message[position]; + position++; + + switch (OnWeaponChangeAttempt(id, wpnid, writesocket)) + { + case 0: + SendWeaponChangeMessage(id, wpnid, writesocket); + break; + case 1: + break; + default: + break; + } + return paketlength; } /** * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int teamchange(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 3; - if(length < paketlength) - { - printf("Invalid packet (teamchange)!\n"); - return length; - } - unsigned char team = message[1]; - unsigned char skin = message[2]; - - switch(OnTeamChangeAttempt(id, team, skin, writesocket)) - { - case 0: - player[id].team = team; - if(skin != 5) player[id].skin = skin; - OnTeamChange(id, team, skin, writesocket); - break; - case 1: - break; - default: - break; - } - return paketlength; + int paketlength = 3; + if (length < paketlength) + { + printf("Invalid packet (teamchange)!\n"); + return length; + } + unsigned char team = message[1]; + unsigned char skin = message[2]; + + switch (OnTeamChangeAttempt(id, team, skin, writesocket)) + { + case 0: + player[id].team = team; + if (skin != 5) + player[id].skin = skin; + OnTeamChange(id, team, skin, writesocket); + break; + case 1: + break; + default: + break; + } + return paketlength; } /** * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param *client pointer to the client information structure * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ -int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) +int ping_serverlist(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket) { - int paketlength = 5; - if(length < paketlength) - { - printf("Invalid packet (ping_serverlist)!\n"); - return length; - } - - unsigned char *tempbuffer = malloc(paketlength); - if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); - - - tempbuffer[0] = 0x01; - tempbuffer[1] = 0x00; - memcpy(tempbuffer+2, message, paketlength); - - udp_send(writesocket, tempbuffer, 5, client); - free(tempbuffer); - return paketlength; + int paketlength = 5; + if (length < paketlength) + { + printf("Invalid packet (ping_serverlist)!\n"); + return length; + } + + unsigned char *tempbuffer = malloc(paketlength); + if (tempbuffer == NULL) + error_exit("Memory error ( ping_serverlist() )"); + + tempbuffer[0] = 0x01; + tempbuffer[1] = 0x00; + memcpy(tempbuffer + 2, message, paketlength); + + udp_send(writesocket, tempbuffer, 5, client); + free(tempbuffer); + return paketlength; } -int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) +int serverinfo_request(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket) { - int paketlength = length; - if(length < 2) - { - printf("Invalid packet (serverinfo_request)!\n"); - return length; - } - - /* - int i; - printf("serverinfo_request (%d): ", message[0]); - for (i = 1; i <= paketlength; i++) - { - printf("%d-", message[i]); - } - printf("(%d)\n", paketlength); - int joinroutine_known(unsigned char *message, int length, int id, int writesocket) - */ - - int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); - if(sv_gamemode != 0) - { - stringsize++; - } - - unsigned char *buffer = malloc(stringsize); - if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); - - int position = 0; - buffer[position] = 1; - position++; - buffer[position] = 0; - position++; - buffer[position] = 0xFB; - position++; - buffer[position] = message[1]; - position++; - - switch(message[1]) - { - case 1: - case 2: - /* - if(message[2] == 0) - { - paketlength = 2; - } - else - { - paketlength = 6; - } - */ - paketlength = 4; - - buffer[position] = GetServerStatus(); - position++; - buffer[position] = u_strlen(sv_name); - position++; - memcpy(buffer+position, sv_name, u_strlen(sv_name)); - position += u_strlen(sv_name); - buffer[position] = u_strlen(sv_map); - position++; - memcpy(buffer+position, sv_map, u_strlen(sv_map)); - position += u_strlen(sv_map); - buffer[position] = onlineplayer; - position++; - buffer[position] = sv_maxplayers; - position++; - if(sv_gamemode != 0) - { - buffer[position] = sv_gamemode; - position++; - } - buffer[position] = bot_count; - position++; - udp_send(writesocket, buffer, stringsize, client); - break; - case 4: - break; - case 5: - break; - default: - break; - } - - free(buffer); - - return paketlength; + int paketlength = length; + if (length < 2) + { + printf("Invalid packet (serverinfo_request)!\n"); + return length; + } + + /* + int i; + printf("serverinfo_request (%d): ", message[0]); + for (i = 1; i <= paketlength; i++) + { + printf("%d-", message[i]); + } + printf("(%d)\n", paketlength); + int joinroutine_known(unsigned char *message, int length, int id, int writesocket) + */ + + int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); + if (sv_gamemode != 0) + { + stringsize++; + } + + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( serverinfo_request() )"); + + int position = 0; + buffer[position] = 1; + position++; + buffer[position] = 0; + position++; + buffer[position] = 0xFB; + position++; + buffer[position] = message[1]; + position++; + + switch (message[1]) + { + case 1: + case 2: + /* + if(message[2] == 0) + { + paketlength = 2; + } + else + { + paketlength = 6; + } + */ + paketlength = 4; + + buffer[position] = GetServerStatus(); + position++; + buffer[position] = u_strlen(sv_name); + position++; + memcpy(buffer + position, sv_name, u_strlen(sv_name)); + position += u_strlen(sv_name); + buffer[position] = u_strlen(sv_map); + position++; + memcpy(buffer + position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); + buffer[position] = onlineplayer; + position++; + buffer[position] = sv_maxplayers; + position++; + if (sv_gamemode != 0) + { + buffer[position] = sv_gamemode; + position++; + } + buffer[position] = bot_count; + position++; + udp_send(writesocket, buffer, stringsize, client); + break; + case 4: + break; + case 5: + break; + default: + break; + } + + free(buffer); + + return paketlength; } -int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) +int joinroutine_unknown(unsigned char *message, int length, + struct sockaddr_in *client, int writesocket) { - int paketlength = length; //Just 2 char read (message[1]) - if(length < 2) - { - printf("Invalid packet (joinroutine_unknown)!\n"); - return length; - } - switch(message[1]) - { - case 0x00: - { - paketlength = 2; - - int i; - for (i = 1; i <= MAX_CLIENTS-1; i++) - { - if (player[i].used != 1) - { - player[i].used = 1; - player[i].ip = client->sin_addr; - player[i].port = client->sin_port; - player[i].joinstatus = 1; - player[i].client_nummer = 4; - player[i].server_nummer = 2; - break; - } - } - int stringsize = 5 + u_strlen(pre_authcode); - unsigned char *buffer = malloc(stringsize); - if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); - - int position = 0; - buffer[position] = 0x01; - position++; - buffer[position] = 0x00; - position++; - buffer[position] = 0xFC; - position++; - buffer[position] = 0x00; - position++; - buffer[position] = u_strlen(pre_authcode); - position++; - memcpy(buffer+position, pre_authcode, u_strlen(pre_authcode)); - - udp_send(writesocket, buffer, stringsize, client); - - free(buffer); - break; - } - default: - printf("Unexpected join data (%d)\n", message[0]); - break; - } - - return paketlength; + int paketlength = length; //Just 2 char read (message[1]) + if (length < 2) + { + printf("Invalid packet (joinroutine_unknown)!\n"); + return length; + } + switch (message[1]) + { + case 0x00: + { + paketlength = 2; + + int i; + for (i = 1; i <= MAX_CLIENTS - 1; i++) + { + if (player[i].used != 1) + { + player[i].used = 1; + player[i].ip = client->sin_addr; + player[i].port = client->sin_port; + player[i].joinstatus = 1; + player[i].client_nummer = 4; + player[i].server_nummer = 2; + break; + } + } + int stringsize = 5 + u_strlen(pre_authcode); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_unknown() )"); + + int position = 0; + buffer[position] = 0x01; + position++; + buffer[position] = 0x00; + position++; + buffer[position] = 0xFC; + position++; + buffer[position] = 0x00; + position++; + buffer[position] = u_strlen(pre_authcode); + position++; + memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); + + udp_send(writesocket, buffer, stringsize, client); + + free(buffer); + break; + } + default: + printf("Unexpected join data (%d)\n", message[0]); + break; + } + + return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 9; - if(paketlength > length) - { - printf("Invalid packet (specpos)!\n"); - return length; - } - int x, y; - - x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; - y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; - - switch(OnSpecmove(id, x, y, writesocket)) - { - case 0: - { - player[id].specposx = x; - player[id].specposy = y; - break; - } - case 1: - { - break; - } - } - return paketlength; + int paketlength = 9; + if (paketlength > length) + { + printf("Invalid packet (specpos)!\n"); + return length; + } + int x, y; + + x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) + | message[1]; + y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) + | message[5]; + + switch (OnSpecmove(id, x, y, writesocket)) + { + case 0: + { + player[id].specposx = x; + player[id].specposy = y; + break; + } + case 1: + { + break; + } + } + return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { - int paketlength=4; - unsigned char team, unknown; - int paketsize; - - if(paketlength > length) - { - printf("Invalid packet (chatmessage)!\n"); - return length; - } - - int position = 0; - position++; - team = message[position]; - position++; - - paketsize = message[position]; - if (paketsize > 255 || paketsize >= (length-position+1)) - { - printf("Message too big\n"); - return length; - } - position++; - paketlength += paketsize; - - unknown = message[position]; - position++; - - unsigned char *string = malloc(paketsize); - if (string == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(string, message+position, paketsize); - string[paketsize] = '\0'; - position += paketsize; - - switch(OnChatMessage(id, string, team, writesocket)) - { - case 0: - break; - default: - printf("Unknown Return value for OnChatMessage()!\n"); - break; - } - - free(string); - - return paketlength; + int paketlength = 4; + unsigned char team, unknown; + int paketsize; + + if (paketlength > length) + { + printf("Invalid packet (chatmessage)!\n"); + return length; + } + + int position = 0; + position++; + team = message[position]; + position++; + + paketsize = message[position]; + if (paketsize > 255 || paketsize >= (length - position + 1)) + { + printf("Message too big\n"); + return length; + } + position++; + paketlength += paketsize; + + unknown = message[position]; + position++; + + unsigned char *string = malloc(paketsize); + if (string == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(string, message + position, paketsize); + string[paketsize] = '\0'; + position += paketsize; + + switch (OnChatMessage(id, string, team, writesocket)) + { + case 0: + break; + default: + printf("Unknown Return value for OnChatMessage()!\n"); + break; + } + + free(string); + + return paketlength; } -int joinroutine_known(unsigned char *message, int length, int id, int writesocket) +int joinroutine_known(unsigned char *message, int length, int id, + int writesocket) { - int paketlength = 2; - if(paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - switch(message[1]) - { - case 0: - { - paketlength = 2; - if(paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - break; - } - case 1: - { - if(player[id].joinstatus == 1) - { - paketlength = 16; // ??? - if(paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - - int position = 2; - //Playername - int stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("Playername too big\n"); - return length; - } - paketlength += stringsize; - position++; - - player[id].name = malloc(stringsize); - if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].name, message+position, stringsize); - player[id].name[stringsize] = '\0'; - position += stringsize; //+1 because after it there is a null byte, so ignore it - - //printf("Player %s connected..\n", player[id].name); - - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("Password too big\n"); - return length; - } - paketlength += stringsize; - position++; - - unsigned char *password = malloc(stringsize); - if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(password, message+position, stringsize); - password[stringsize] = '\0'; - position += stringsize; - - //printf("\tPassword: "); - /* - int i; - for (i = 0; i <= u_strlen(password); i++) - { - printf("%d-", password[i]); - } - printf("\n"); - */ - - //Encryption String - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("Encryption too big\n"); - return length; - } - paketlength += stringsize; - position++; - - unsigned char *encryption1 = malloc(stringsize); - if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(encryption1, message+position, stringsize); - encryption1[stringsize] = '\0'; - position += stringsize; - - //printf("\tEncryptionstring: %s\n", encryption1); - - //Player Version - player[id].version = message[position]; - position++; - //printf("\tVersion: %d\n", player[id].version); - position++; //Null-byte - - - //USGN ID - player[id].usgn = malloc(sizeof(unsigned short)); - if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].usgn, message+position, 2); //sizeof(unsigned short) == 2 - position += 4; //2 bytes + 2 null bytes -/* -#else - *player[id].usgn = endian_swap_short(player[id].usgn); -#endif -*/ - //printf("\tUSGN-ID: %u\n", *player[id].usgn); - - - //Spraylogo - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("Spraylogoname too big\n"); - return length; - }; - paketlength += stringsize; - position++; - - player[id].spraylogo = malloc(stringsize); - if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].spraylogo, message+position, stringsize); - player[id].spraylogo[stringsize] = '\0'; - position += stringsize; - - //printf("\tSpraylogo: %s\n", player[id].spraylogo); - - - - //Map-Hash - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("Map-Hash too big\n"); - return length; - } - paketlength += stringsize; - position++; - - unsigned char *maphash= malloc(stringsize); - if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(maphash, message+position, stringsize); - maphash[stringsize] = '\0'; - position += stringsize; - - //printf("\tMap-Hash: %s\n", maphash); - - position++; //Nullbyte - - //WIN - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("WIN too big\n"); - return length; - } - paketlength += stringsize; - position++; - - player[id].win= malloc(stringsize); - if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(player[id].win, message+position, stringsize); - player[id].win[stringsize] = '\0'; - position += stringsize; - - - //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); - - unsigned char *buffer = NULL; - stringsize = 0; - int tempstatus = CheckPlayerData(password); - switch(tempstatus) - { - case 0x00: - stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 2; - position++; - buffer[position] = 0; //Normal - position++; - buffer[position] = id; - position++; - buffer[position] = u_strlen(sv_map); - position++; - memcpy(buffer+position, sv_map, u_strlen(sv_map)); - position += u_strlen(sv_map); - buffer[position] = u_strlen(pre_authcode); - position++; - memcpy(buffer+position, pre_authcode, u_strlen(pre_authcode)); - position += u_strlen(pre_authcode); - player[id].joinstatus = 2; - break; - - default: - { - stringsize = 3; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 2; - position++; - buffer[position] = tempstatus; //Everyone is banned (just for testing) - position++; - player[id].joinstatus = 0; - break; - } - - } - //stringsize = 16 + u_strlen(sv_map); - - /* - 0 - Normal - 1 - Password wrong - 2 - USGN only - 3 - Server full - 4 - Banned - 5 - Another Game Version - 6 - ?? - 7 - Can't validate user (USGN offline) - 8 - ?? - 9 - Connection already exists - 10 - Wrong client (pre_authcode) - 11 - Diffrent map (temp, etc.) - 12 - Map unknown (maptransfer disabled) - 13++ - Failed to join - */ - - if(stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); - - free(encryption1); - free(maphash); - free(buffer); - - onlineplayer++; - } - else - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - case 3: - { - if(player[id].joinstatus == 2) - { - int position = 2; - - paketlength = 5; - if(paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - - //Map-Hash - int stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("Map-Hash too big\n"); - return length; - } - position++; - - unsigned char *maphash = malloc(stringsize); - if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(maphash, message+position, stringsize); - maphash[stringsize] = '\0'; - position += stringsize; - paketlength += stringsize; - - //printf("\tMaphash: %s\n", maphash); - - //pre_authcode_respond - stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("pre_authcon_respond too big\n"); - return length; - } - position++; - - unsigned char *pre_authcode_respond = malloc(stringsize); - if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(pre_authcode_respond, message+position, stringsize); - pre_authcode_respond[stringsize] = '\0'; - position += stringsize; - paketlength += stringsize; - - //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); - - //Player Version - //unsigned char mapstatus = message[position]; //avoid warning - position++; - //printf("\tMapstatus: %d\n", mapstatus); - - free(pre_authcode_respond); - free(maphash); - - //Respond - stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 4; - position++; - buffer[position] = 0; //CheckPlayerData() - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - player[id].joinstatus = 3; - } - else - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - case 5: - { - if(player[id].joinstatus == 3) - { - int position = 2; - - paketlength = 3; - if(paketlength > length) - { - printf("Invalid packet (joinroutine_known)!\n"); - return length; - } - //Map-Hash - int stringsize = message[position]; - if (stringsize > 255 || stringsize >= (length-position+1)) - { - printf("Mapname too big\n"); - return length; - } - position++; - - unsigned char *mapname = malloc(stringsize); - if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - memcpy(mapname, message+position, stringsize); - mapname[stringsize] = '\0'; - position += stringsize; - paketlength += stringsize; - - //printf("\tMapname: %s\n", mapname); - - - //----------- ServerData ----------- - - stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 6; - position++; - buffer[position] = 0; //CheckPlayerData() - position++; - - buffer[position] = u_strlen(sv_map); - position++; - memcpy(buffer+position, sv_map, u_strlen(sv_map)); - position += u_strlen(sv_map); - - buffer[position] = u_strlen(sv_name); - position++; - memcpy(buffer+position, sv_name, u_strlen(sv_name)); - position += u_strlen(sv_name); - - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = sv_friendlyfire; - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = mp_roundtime; - position++; - buffer[position] = mp_freezetime; - position++; - buffer[position] = mp_c4timer; - position++; - buffer[position] = 32; //Unknown - position++; - buffer[position] = 124; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 1; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = sv_maxplayers; - position++; - buffer[position] = sv_fow; - position++; - buffer[position] = mp_specmode; - position++; - buffer[position] = sv_gamemode; - position++; - buffer[position] = mp_respawndelay; - position++; - buffer[position] = mp_infammo; - position++; - buffer[position] = 3; //u_strlen ACK - position++; - buffer[position] = 65; //A - position++; - buffer[position] = 67; //C - position++; - buffer[position] = 75; //K - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- PlayerData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 1; - position++; - buffer[position] = onlineplayer; - position++; - - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if(player[i].used == 1 && player[i].joinstatus >= 1 && i != id) - { - unsigned char *encodedname; - encodedname = GetEncodedString(player[i].name, u_strlen(player[i].name)); - unsigned short *deaths = &player[i].deaths; - unsigned short tempscore = (unsigned)(player[i].deaths + 1000); - unsigned short *score = &tempscore; - - unsigned short tempx = (player[i].x); - unsigned short tempy = (player[i].y); - unsigned short *x = &tempx; - unsigned short *y = &tempy; - - float *ptemprotation = &player[i].rotation; - - int playersize = 25 + u_strlen(encodedname); - buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - buffer[position] = i; - position++; - - buffer[position] = u_strlen(encodedname); - position++; - memcpy(buffer+position, encodedname, u_strlen(encodedname)); - position += u_strlen(encodedname); - free(encodedname); - - buffer[position] = 0; //Unknown - position++; - buffer[position] = player[i].team; - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - /* - buffer[position] = score[0]; //Deaths - position++; - buffer[position] = score[1]; //Deaths - position++; - */ - memcpy(buffer+position, score, 2); - position += 2; - /* - buffer[position] = deaths[0]; //Deaths - position++; - buffer[position] = deaths[1]; //Deaths - position++; - */ - memcpy(buffer+position, deaths, 2); - position += 2; - memcpy(buffer+position, x, 2); - position += 2; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - memcpy(buffer+position, y, 2); - position += 2; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = ptemprotation[0]; //Rotation - position++; - buffer[position] = ptemprotation[1]; //Rotation - position++; - buffer[position] = player[i].health; //Health - position++; - buffer[position] = player[i].armor; //Armor - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe - position++; - buffer[position] = 0; //Unknown - position++; - /* - 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 - 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 - 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 - 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 - e8 03 00 00 12 01 00 00 01 03 - e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 - e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 - 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 - */ - } - } - if(1) - { - unsigned char *encodedname; - encodedname = GetEncodedString(player[id].name, u_strlen(player[id].name)); - - int playersize = 25 + u_strlen(encodedname); - buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - buffer[position] = id; - position++; - - - buffer[position] = u_strlen(encodedname); - position++; - memcpy(buffer+position, encodedname, u_strlen(encodedname)); - position += u_strlen(encodedname); - free(encodedname); - - buffer[position] = 0; //Unknown - position++; - buffer[position] = player[id].team; - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 232; //Unknown - position++; - buffer[position] = 3; //Unknown - position++; - buffer[position] = 0; //Deaths - position++; - buffer[position] = 0; //Deaths - position++; - buffer[position] = 0; //X - position++; - buffer[position] = 0; //X - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Y - position++; - buffer[position] = 0; //Y - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Health - position++; - buffer[position] = 0; //Armor - position++; - buffer[position] = 0; //Unknown - position++; - buffer[position] = 0; //Aktuelle Waffe 50 = Knife - position++; - buffer[position] = 0; //Unknown - position++; - } - - SendToPlayer(buffer, position, id, 1, writesocket); - free(buffer); - - //----------- PlayerData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 1; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- HostageData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 2; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- ItemData ----------- - - /* - fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 - */ - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 3; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- EnityData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 4; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- DynamicObjectData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 5; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- ProjectileData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 6; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- DynamicObjectImageData ----------- - stringsize = 4; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 7; //third payload - position++; - buffer[position] = 0; - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - //----------- Final ACK ----------- - stringsize = 7; - buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); - - position = 0; - - buffer[position] = 252; - position++; - buffer[position] = 7; - position++; - buffer[position] = 200; //third payload - position++; - buffer[position] = 3; //u_strlen ACK - position++; - buffer[position] = 65; //A - position++; - buffer[position] = 67; //C - position++; - buffer[position] = 75; //K - position++; - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); - - player[id].joinstatus = 4; - free(mapname); - - OnJoin(id, writesocket); - } - else - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - default: - { - printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); - } - break; - } - - return paketlength; + int paketlength = 2; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + switch (message[1]) + { + case 0: + { + paketlength = 2; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + break; + } + case 1: + { + if (player[id].joinstatus == 1) + { + paketlength = 16; // ??? + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + + int position = 2; + //Playername + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Playername too big\n"); + return length; + } + paketlength += stringsize; + position++; + + player[id].name = malloc(stringsize); + if (player[id].name == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].name, message + position, stringsize); + player[id].name[stringsize] = '\0'; + position += stringsize; //+1 because after it there is a null byte, so ignore it + + //printf("Player %s connected..\n", player[id].name); + + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Password too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *password = malloc(stringsize); + if (password == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(password, message + position, stringsize); + password[stringsize] = '\0'; + position += stringsize; + + //printf("\tPassword: "); + /* + int i; + for (i = 0; i <= u_strlen(password); i++) + { + printf("%d-", password[i]); + } + printf("\n"); + */ + + //Encryption String + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Encryption too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *encryption1 = malloc(stringsize); + if (encryption1 == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(encryption1, message + position, stringsize); + encryption1[stringsize] = '\0'; + position += stringsize; + + //printf("\tEncryptionstring: %s\n", encryption1); + + //Player Version + player[id].version = message[position]; + position++; + //printf("\tVersion: %d\n", player[id].version); + position++; //Null-byte + + + //USGN ID + player[id].usgn = malloc(sizeof(unsigned short)); + if (player[id].usgn == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].usgn, message + position, 2); //sizeof(unsigned short) == 2 + position += 4; //2 bytes + 2 null bytes + /* + #else + *player[id].usgn = endian_swap_short(player[id].usgn); + #endif + */ + //printf("\tUSGN-ID: %u\n", *player[id].usgn); + + + //Spraylogo + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Spraylogoname too big\n"); + return length; + }; + paketlength += stringsize; + position++; + + player[id].spraylogo = malloc(stringsize); + if (player[id].spraylogo == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].spraylogo, message + position, stringsize); + player[id].spraylogo[stringsize] = '\0'; + position += stringsize; + + //printf("\tSpraylogo: %s\n", player[id].spraylogo); + + + //Map-Hash + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Map-Hash too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *maphash = malloc(stringsize); + if (maphash == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(maphash, message + position, stringsize); + maphash[stringsize] = '\0'; + position += stringsize; + + //printf("\tMap-Hash: %s\n", maphash); + + position++; //Nullbyte + + //WIN + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("WIN too big\n"); + return length; + } + paketlength += stringsize; + position++; + + player[id].win = malloc(stringsize); + if (player[id].win == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].win, message + position, stringsize); + player[id].win[stringsize] = '\0'; + position += stringsize; + + //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); + + unsigned char *buffer = NULL; + stringsize = 0; + int tempstatus = CheckPlayerData(password); + switch (tempstatus) + { + case 0x00: + stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 2; + position++; + buffer[position] = 0; //Normal + position++; + buffer[position] = id; + position++; + buffer[position] = u_strlen(sv_map); + position++; + memcpy(buffer + position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); + buffer[position] = u_strlen(pre_authcode); + position++; + memcpy(buffer + position, pre_authcode, u_strlen(pre_authcode)); + position += u_strlen(pre_authcode); + player[id].joinstatus = 2; + break; + + default: + { + stringsize = 3; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 2; + position++; + buffer[position] = tempstatus; //Everyone is banned (just for testing) + position++; + player[id].joinstatus = 0; + break; + } + + } + //stringsize = 16 + u_strlen(sv_map); + + /* + 0 - Normal + 1 - Password wrong + 2 - USGN only + 3 - Server full + 4 - Banned + 5 - Another Game Version + 6 - ?? + 7 - Can't validate user (USGN offline) + 8 - ?? + 9 - Connection already exists + 10 - Wrong client (pre_authcode) + 11 - Diffrent map (temp, etc.) + 12 - Map unknown (maptransfer disabled) + 13++ - Failed to join + */ + + if (stringsize != 0) + SendToPlayer(buffer, stringsize, id, 1, writesocket); + + free(encryption1); + free(maphash); + free(buffer); + + onlineplayer++; + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + case 3: + { + if (player[id].joinstatus == 2) + { + int position = 2; + + paketlength = 5; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + + //Map-Hash + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Map-Hash too big\n"); + return length; + } + position++; + + unsigned char *maphash = malloc(stringsize); + if (maphash == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(maphash, message + position, stringsize); + maphash[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tMaphash: %s\n", maphash); + + //pre_authcode_respond + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("pre_authcon_respond too big\n"); + return length; + } + position++; + + unsigned char *pre_authcode_respond = malloc(stringsize); + if (pre_authcode_respond == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(pre_authcode_respond, message + position, stringsize); + pre_authcode_respond[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); + + //Player Version + //unsigned char mapstatus = message[position]; //avoid warning + position++; + //printf("\tMapstatus: %d\n", mapstatus); + + free(pre_authcode_respond); + free(maphash); + + //Respond + stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 4; + position++; + buffer[position] = 0; //CheckPlayerData() + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + player[id].joinstatus = 3; + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + case 5: + { + if (player[id].joinstatus == 3) + { + int position = 2; + + paketlength = 3; + if (paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + //Map-Hash + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length - position + 1)) + { + printf("Mapname too big\n"); + return length; + } + position++; + + unsigned char *mapname = malloc(stringsize); + if (mapname == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(mapname, message + position, stringsize); + mapname[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tMapname: %s\n", mapname); + + + //----------- ServerData ----------- + + stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 6; + position++; + buffer[position] = 0; //CheckPlayerData() + position++; + + buffer[position] = u_strlen(sv_map); + position++; + memcpy(buffer + position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); + + buffer[position] = u_strlen(sv_name); + position++; + memcpy(buffer + position, sv_name, u_strlen(sv_name)); + position += u_strlen(sv_name); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = sv_friendlyfire; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = mp_roundtime; + position++; + buffer[position] = mp_freezetime; + position++; + buffer[position] = mp_c4timer; + position++; + buffer[position] = 32; //Unknown + position++; + buffer[position] = 124; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 1; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = sv_maxplayers; + position++; + buffer[position] = sv_fow; + position++; + buffer[position] = mp_specmode; + position++; + buffer[position] = sv_gamemode; + position++; + buffer[position] = mp_respawndelay; + position++; + buffer[position] = mp_infammo; + position++; + buffer[position] = 3; //u_strlen ACK + position++; + buffer[position] = 65; //A + position++; + buffer[position] = 67; //C + position++; + buffer[position] = 75; //K + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- PlayerData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 1; + position++; + buffer[position] = onlineplayer; + position++; + + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 1 && i != id) + { + unsigned char *encodedname; + encodedname = GetEncodedString(player[i].name, u_strlen( + player[i].name)); + unsigned short *deaths = &player[i].deaths; + unsigned short tempscore = (unsigned) (player[i].deaths + + 1000); + unsigned short *score = &tempscore; + + unsigned short tempx = (player[i].x); + unsigned short tempy = (player[i].y); + unsigned short *x = &tempx; + unsigned short *y = &tempy; + + float *ptemprotation = &player[i].rotation; + + int playersize = 25 + u_strlen(encodedname); + buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + buffer[position] = i; + position++; + + buffer[position] = u_strlen(encodedname); + position++; + memcpy(buffer + position, encodedname, + u_strlen(encodedname)); + position += u_strlen(encodedname); + free(encodedname); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = player[i].team; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + /* + buffer[position] = score[0]; //Deaths + position++; + buffer[position] = score[1]; //Deaths + position++; + */ + memcpy(buffer + position, score, 2); + position += 2; + /* + buffer[position] = deaths[0]; //Deaths + position++; + buffer[position] = deaths[1]; //Deaths + position++; + */ + memcpy(buffer + position, deaths, 2); + position += 2; + memcpy(buffer + position, x, 2); + position += 2; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + memcpy(buffer + position, y, 2); + position += 2; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = ptemprotation[0]; //Rotation + position++; + buffer[position] = ptemprotation[1]; //Rotation + position++; + buffer[position] = player[i].health; //Health + position++; + buffer[position] = player[i].armor; //Armor + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] + = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe + position++; + buffer[position] = 0; //Unknown + position++; + /* + 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 + 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 + 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 + 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 + e8 03 00 00 12 01 00 00 01 03 + e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 + e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 + 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 + */ + } + } + if (1) + { + unsigned char *encodedname; + encodedname = GetEncodedString(player[id].name, u_strlen( + player[id].name)); + + int playersize = 25 + u_strlen(encodedname); + buffer = realloc(buffer, position + 1 + playersize); //+1 because e.g. buffer[10] are 11 chars + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + buffer[position] = id; + position++; + + buffer[position] = u_strlen(encodedname); + position++; + memcpy(buffer + position, encodedname, u_strlen(encodedname)); + position += u_strlen(encodedname); + free(encodedname); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = player[id].team; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 232; //Unknown + position++; + buffer[position] = 3; //Unknown + position++; + buffer[position] = 0; //Deaths + position++; + buffer[position] = 0; //Deaths + position++; + buffer[position] = 0; //X + position++; + buffer[position] = 0; //X + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Y + position++; + buffer[position] = 0; //Y + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Health + position++; + buffer[position] = 0; //Armor + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Aktuelle Waffe 50 = Knife + position++; + buffer[position] = 0; //Unknown + position++; + } + + SendToPlayer(buffer, position, id, 1, writesocket); + free(buffer); + + //----------- PlayerData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 1; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- HostageData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 2; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- ItemData ----------- + + /* + fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 + */ + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 3; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- EnityData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 4; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- DynamicObjectData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 5; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- ProjectileData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 6; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- DynamicObjectImageData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 7; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- Final ACK ----------- + stringsize = 7; + buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 200; //third payload + position++; + buffer[position] = 3; //u_strlen ACK + position++; + buffer[position] = 65; //A + position++; + buffer[position] = 67; //C + position++; + buffer[position] = 75; //K + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + player[id].joinstatus = 4; + free(mapname); + + OnJoin(id, writesocket); + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + default: + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + + return paketlength; } int leave(int id, int writesocket) { - OnLeave(id, writesocket); + OnLeave(id, writesocket); - free(player[id].name); - free(player[id].usgn); - free(player[id].spraylogo); - free(player[id].win); + free(player[id].name); + free(player[id].usgn); + free(player[id].spraylogo); + free(player[id].win); - player[id].name = NULL; - player[id].usgn = NULL; - player[id].spraylogo = NULL; - player[id].win = NULL; + player[id].name = NULL; + player[id].usgn = NULL; + player[id].spraylogo = NULL; + player[id].win = NULL; - onlineplayer--; + onlineplayer--; - ClearPlayer(id); + ClearPlayer(id); - return 2; + return 2; } int reload(unsigned char *message, int length, int id, int writesocket) { - int paketlength = 2; - if(length < paketlength) - { - printf("Invalid packet (buy)!\n"); - return length; - } - - int position = 1; - int status; - - status = message[position]; - position++; - - if(status == 1) - { - SendReloadMessage(id, 1, writesocket); - player[id].reloading = player[id].actualweapon; - player[id].reloadtimer = mtime()+weapons[player[id].slot[player[id].actualweapon].id].reloadtime; - } - return paketlength; + int paketlength = 2; + if (length < paketlength) + { + printf("Invalid packet (buy)!\n"); + return length; + } + + int position = 1; + int status; + + status = message[position]; + position++; + + if (status == 1) + { + SendReloadMessage(id, 1, writesocket); + player[id].reloading = player[id].actualweapon; + player[id].reloadtimer + = mtime() + + weapons[player[id].slot[player[id].actualweapon].id].reloadtime; + } + return paketlength; } diff --git a/src/respond_messages.c b/src/respond_messages.c index 32f040f..af65bbc 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,595 +1,624 @@ -#include "../include/respond_messages.h" +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ +#include "../include/respond_messages.h" -void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) +void SendSpawnMessage(int id, unsigned short x, unsigned short y, + int writesocket) { - int stringsize = 11; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); - - int position = 0; - - unsigned short *spawnx = &x; - unsigned short *spawny = &y; - unsigned short *pmoney = &player[id].money; - - buffer[position] = 21; - position++; - buffer[position] = id; - position++; - memcpy(buffer+position, spawnx, 2); - position += 2; - memcpy(buffer+position, spawny, 2); - position += 2; - buffer[position] = 50; //Team - position++; - buffer[position] = 0; - position++; - /* - buffer[position] = pmoney[1]; //Money - position++; - buffer[position] = pmoney[0]; // Money - position++; - */ - memcpy(buffer+position, pmoney, 2); - position += 2; - - int i, count; - count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); - buffer[position] = count; - position++; - - buffer = realloc(buffer, stringsize + count); - if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); - - for(i = 0; i <= count-1; i++) - { - buffer[position] = startweapons[i]; - position++; - - GivePlayerWeapon(id, startweapons[i]); - if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 - } - - /* - int count, i; - count = 0; - for(i = 0; i <= 10; i++) - { - if(player[id].slot[i].id != 0) - { - count++; - } - } - buffer[position] = count; //Count - position++; - - buffer = realloc(buffer, stringsize + count); - if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); - - for(i = 0; i <= 10; i++) - { - if(player[id].slot[i].id != 0) - { - buffer[position] = player[id].slot[i].id; - position++; - } - } - */ - - SendToAll(buffer, stringsize + count, 1, writesocket); - - free(buffer); + int stringsize = 11; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendSpawnMessage() )\n"); + + int position = 0; + + unsigned short *spawnx = &x; + unsigned short *spawny = &y; + unsigned short *pmoney = &player[id].money; + + buffer[position] = 21; + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, spawnx, 2); + position += 2; + memcpy(buffer + position, spawny, 2); + position += 2; + buffer[position] = 50; //Team + position++; + buffer[position] = 0; + position++; + /* + buffer[position] = pmoney[1]; //Money + position++; + buffer[position] = pmoney[0]; // Money + position++; + */ + memcpy(buffer + position, pmoney, 2); + position += 2; + + int i, count; + count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); + buffer[position] = count; + position++; + + buffer = realloc(buffer, stringsize + count); + if (buffer == NULL) + error_exit("Memory error ( SendSpawnMessage() )\n"); + + for (i = 0; i <= count - 1; i++) + { + buffer[position] = startweapons[i]; + position++; + + GivePlayerWeapon(id, startweapons[i]); + if (startweapons[i] == 50) + player[id].actualweapon = i; //else 0 + } + + /* + int count, i; + count = 0; + for(i = 0; i <= 10; i++) + { + if(player[id].slot[i].id != 0) + { + count++; + } + } + buffer[position] = count; //Count + position++; + + buffer = realloc(buffer, stringsize + count); + if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); + + for(i = 0; i <= 10; i++) + { + if(player[id].slot[i].id != 0) + { + buffer[position] = player[id].slot[i].id; + position++; + } + } + */ + + SendToAll(buffer, stringsize + count, 1, writesocket); + + free(buffer); } void SendAdvancedFireMessage(int id, int status, int writesocket) { - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendFireMessage() )\n"); - int position = 0; + int position = 0; - buffer[position] = 8; - position++; - buffer[position] = id; - position++; - buffer[position] = status; - position++; + buffer[position] = 8; + position++; + buffer[position] = id; + position++; + buffer[position] = status; + position++; - SendToAll(buffer, stringsize, 1, writesocket); + SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); + free(buffer); } void SendFireMessage(int id, int writesocket) { - int stringsize = 2; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); + int stringsize = 2; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendFireMessage() )\n"); - int position = 0; + int position = 0; - buffer[position] = 7; - position++; - buffer[position] = id; - position++; + buffer[position] = 7; + position++; + buffer[position] = id; + position++; - SendToAll(buffer, stringsize, 1, writesocket); + SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); + free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { - int stringsize = 6; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendBuyMessage() )\n"); - int position = 0; + int position = 0; - buffer[position] = 23; - position++; - buffer[position] = id; - position++; - buffer[position] = wpnid; - position++; - memcpy(buffer+position, &player[id].money, 2); - position += 2; - buffer[position] = 0; - position++; + buffer[position] = 23; + position++; + buffer[position] = id; + position++; + buffer[position] = wpnid; + position++; + memcpy(buffer + position, &player[id].money, 2); + position += 2; + buffer[position] = 0; + position++; - SendToPlayer(buffer, stringsize, id, 1, writesocket); + SendToPlayer(buffer, stringsize, id, 1, writesocket); - free(buffer); + free(buffer); - SendWeaponChangeMessage(id, wpnid, writesocket); + SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { - int stringsize = 5; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); - - int position = 0; + int stringsize = 5; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendHitMessage() )\n"); - buffer[position] = 17; - position++; - buffer[position] = id; - position++; - buffer[position] = victim; - position++; - buffer[position] = health; - position++; - buffer[position] = 0; - position++; + int position = 0; + buffer[position] = 17; + position++; + buffer[position] = id; + position++; + buffer[position] = victim; + position++; + buffer[position] = health; + position++; + buffer[position] = 0; + position++; - SendToAll(buffer, stringsize, 1, writesocket); + SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); + free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { - int stringsize = 4; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); + int stringsize = 4; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendWeaponChangeMessage() )\n"); - int position = 0; + int position = 0; - buffer[position] = 9; - position++; - buffer[position] = id; - position++; - buffer[position] = wpnid; - position++; - buffer[position] = 0; - position++; + buffer[position] = 9; + position++; + buffer[position] = id; + position++; + buffer[position] = wpnid; + position++; + buffer[position] = 0; + position++; - SendToAll(buffer, stringsize, 1, writesocket); + SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); + free(buffer); } -void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) +void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, + int writesocket) { - int stringsize = 6; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendSpawnMessage() )\n"); - int position = 0; + int position = 0; - unsigned short *px = &x; - unsigned short *py = &y; + unsigned short *px = &x; + unsigned short *py = &y; - if(status == 0) buffer[position] = 11; - else if(status == 1) buffer[position] = 10; + if (status == 0) + buffer[position] = 11; + else if (status == 1) + buffer[position] = 10; - position++; - buffer[position] = id; - position++; - memcpy(buffer+position, px, 2); - position += 2; - memcpy(buffer+position, py, 2); - position += 2; + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, px, 2); + position += 2; + memcpy(buffer + position, py, 2); + position += 2; - SendToAllOther(id, buffer, stringsize, 1, writesocket); + SendToAllOther(id, buffer, stringsize, 1, writesocket); - free(buffer); + free(buffer); } -void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) +void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, + float rotation, int writesocket) { - int stringsize = 10; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); + int stringsize = 10; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendPosRotUpdate() )\n"); - int position = 0; + int position = 0; - unsigned short *px = &x; - unsigned short *py = &y; - //if(rotation > 180) rotation = (rotation - 360); - //unsigned short *protation = &rotation; //2 Bytes cut off + unsigned short *px = &x; + unsigned short *py = &y; + //if(rotation > 180) rotation = (rotation - 360); + //unsigned short *protation = &rotation; //2 Bytes cut off - if(status == 0) buffer[position] = 14; - else if(status == 1) buffer[position] = 13; + if (status == 0) + buffer[position] = 14; + else if (status == 1) + buffer[position] = 13; - position++; - buffer[position] = id; - position++; - memcpy(buffer+position, px, 2); - position += 2; - memcpy(buffer+position, py, 2); - position += 2; - memcpy(buffer+position, &rotation, 4); - position += 4; + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, px, 2); + position += 2; + memcpy(buffer + position, py, 2); + position += 2; + memcpy(buffer + position, &rotation, 4); + position += 4; - SendToAllOther(id, buffer, stringsize, 1, writesocket); + SendToAllOther(id, buffer, stringsize, 1, writesocket); - free(buffer); + free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { - int stringsize = 6; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendRotUpdate() )\n"); - int position = 0; - //if(rotation > 180) rotation = (rotation - 360); + int position = 0; + //if(rotation > 180) rotation = (rotation - 360); - buffer[position] = 12; - position++; - buffer[position] = id; - position++; - memcpy(buffer+position, &rotation, sizeof(float)); + buffer[position] = 12; + position++; + buffer[position] = id; + position++; + memcpy(buffer + position, &rotation, sizeof(float)); - SendToAllOther(id, buffer, stringsize, 1, writesocket); + SendToAllOther(id, buffer, stringsize, 1, writesocket); - free(buffer); + free(buffer); } - void SendMessageToPlayer(int id, char *message, int status, int writesocket) { - /* - 1 - Chat - 2 - Screen - 3 - Console - 4 - Crash - */ - int stringsize = 5 + strlen(message); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); - - int position = 0; - - buffer[position] = 240; - position++; - buffer[position] = 0; - position++; - buffer[position] = status; - position++; - buffer[position] = strlen(message); - position++; - buffer[position] = 0; - position++; - memcpy(buffer+position, message, strlen(message)); - position += strlen(message); - - SendToPlayer(buffer, stringsize, id, 1, writesocket); - - switch(status) - { - case 1: - printf("To %s (Chat): %s\n", player[id].name ,message); - break; - case 2: - printf("To %s (Screen): %s\n", player[id].name ,message); - break; - case 3: - printf("To %s (Console): %s\n", player[id].name ,message); - break; - default: - printf("Unknown status (SendMessageToPlayer())!\n"); - break; - } - - free(buffer); + /* + 1 - Chat + 2 - Screen + 3 - Console + 4 - Crash + */ + int stringsize = 5 + strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = 0; + position++; + buffer[position] = status; + position++; + buffer[position] = strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer + position, message, strlen(message)); + position += strlen(message); + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + + switch (status) + { + case 1: + printf("To %s (Chat): %s\n", player[id].name ,message); + break; + case 2: + printf("To %s (Screen): %s\n", player[id].name ,message); + break; + case 3: + printf("To %s (Console): %s\n", player[id].name ,message); + break; + default: + printf("Unknown status (SendMessageToPlayer())!\n"); + break; + } + + free(buffer); } -void SendMessageToAll(unsigned char *message, int status, int writesocket) +void SendMessageToAll(char *message, int status, int writesocket) { - /* - 1 - Chat - 2 - Screen - 3 - Console - 4 - Crash - */ - int stringsize = 5 + u_strlen(message); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); - - int position = 0; - - buffer[position] = 240; - position++; - buffer[position] = 0; - position++; - buffer[position] = status; - position++; - buffer[position] = u_strlen(message); - position++; - buffer[position] = 0; - position++; - memcpy(buffer+position, message, u_strlen(message)); - position += u_strlen(message); - - SendToAll(buffer, stringsize, 1, writesocket); - - switch(status) - { - case 1: - printf("To All (Chat): %s\n", message); - break; - case 2: - printf("To All (Screen): %s\n", message); - break; - case 3: - printf("To All (Console): %s\n", message); - break; - default: - printf("Unknown status (SendMessageToAll())!\n"); - break; - } - - - free(buffer); -} + /* + 1 - Chat + 2 - Screen + 3 - Console + 4 - Crash + */ + int stringsize = 5 + strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendChatMessage() )\n"); + int position = 0; + buffer[position] = 240; + position++; + buffer[position] = 0; + position++; + buffer[position] = status; + position++; + buffer[position] = strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer + position, message, strlen(message)); + position += strlen(message); + + SendToAll(buffer, stringsize, 1, writesocket); + + switch (status) + { + case 1: + printf("To All (Chat): %s\n", message); + break; + case 2: + printf("To All (Screen): %s\n", message); + break; + case 3: + printf("To All (Console): %s\n", message); + break; + default: + printf("Unknown status (SendMessageToAll())!\n"); + break; + } + + free(buffer); +} void SendJoinMessage(int id, int writesocket) { - int stringsize = 4 + u_strlen(player[id].name); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); + int stringsize = 4 + u_strlen(player[id].name); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendJoinMessage() )\n"); - int position = 0; + int position = 0; - buffer[position] = 248; - position++; - buffer[position] = id; - position++; - buffer[position] = u_strlen(player[id].name); - position++; + buffer[position] = 248; + position++; + buffer[position] = id; + position++; + buffer[position] = u_strlen(player[id].name); + position++; - memcpy(buffer+position, player[id].name, u_strlen(player[id].name)); - position += u_strlen(player[id].name); + memcpy(buffer + position, player[id].name, u_strlen(player[id].name)); + position += u_strlen(player[id].name); - buffer[position] = 0; //u_strlen ACK - position++; + buffer[position] = 0; //u_strlen ACK + position++; - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); } void SendLeaveMessage(int id, int writesocket) { - if(player[id].joinstatus >= 4) - { - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); - int position = 0; - - buffer[position] = 253; - position++; - buffer[position] = id; - position++; - buffer[position] = 0; //u_strlen ACK - position++; - - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); - } + if (player[id].joinstatus >= 4) + { + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendLeaveMessage() )\n"); + int position = 0; + + buffer[position] = 253; + position++; + buffer[position] = id; + position++; + buffer[position] = 0; //u_strlen ACK + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); + } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { - int stringsize = 5 + u_strlen(message); - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); - - int position = 0; - - buffer[position] = 240; - position++; - buffer[position] = id; - position++; - buffer[position] = team; - position++; - buffer[position] = u_strlen(message); - position++; - buffer[position] = 0; - position++; - memcpy(buffer+position, message, u_strlen(message)); - position += u_strlen(message); - if(team == 1) - { - SendToAll(buffer, stringsize, 1, writesocket); - } - else if(team == 2) - { - SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); - } - free(buffer); + int stringsize = 5 + u_strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = id; + position++; + buffer[position] = team; + position++; + buffer[position] = u_strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer + position, message, u_strlen(message)); + position += u_strlen(message); + if (team == 1) + { + SendToAll(buffer, stringsize, 1, writesocket); + } + else if (team == 2) + { + SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); + } + free(buffer); } -void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) +void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, + int writesocket) { - int stringsize = 4; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); - - int position = 0; + int stringsize = 4; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendJoinMessage() )\n"); - buffer[position] = 20; - position++; - buffer[position] = id; - position++; - buffer[position] = team; - position++; - buffer[position] = skin; - position++; + int position = 0; + buffer[position] = 20; + position++; + buffer[position] = id; + position++; + buffer[position] = team; + position++; + buffer[position] = skin; + position++; - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); } -void PingAllPlayer(int writesocket, time_t firsttime) +void PingAllPlayer(int writesocket, time_t *firsttime) { - time_t actualtime; - time(&actualtime); - if(1 == 2)//if(actualtime >= (firsttime + 5)) //FIXME will be executed many many times per sec - { - firsttime = actualtime; - SendPingList(writesocket); - - //SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status - int i; - for(i = 1; i <= sv_maxplayers; i++) - { - if(player[i].used == 1 && player[i].joinstatus >= 4) - { - int stringsize = 5; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); - - int position = 0; - - buffer[position] = 249; - position++; - buffer[position] = 0; - position++; - buffer[position] = 32; - position++; - buffer[position] = 191; - position++; - buffer[position] = 0; - position++; - - player[i].start = mtime(); - - SendToPlayer(buffer, stringsize, i, 0, writesocket); - - free(buffer); - } - - } - } + time_t actualtime; + time(&actualtime); + if (actualtime >= (*firsttime + 5)) + { + *firsttime = actualtime; + SendPingList(writesocket); + + SendMessageToAll("This is an alpha version! Don't play at it!", 1, + writesocket); //Do not remove or change this until server reaches beta status + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4) + { + int stringsize = 5; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 249; + position++; + buffer[position] = 0; + position++; + buffer[position] = 32; + position++; + buffer[position] = 191; + position++; + buffer[position] = 0; + position++; + + player[i].start = mtime(); + + SendToPlayer(buffer, stringsize, i, 0, writesocket); + + free(buffer); + } + + } + } } void SendReloadMessage(int id, int status, int writesocket) { - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); - - int position = 0; + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) + error_exit("Memory error ( SendReloadMessage() )\n"); - buffer[position] = 16; - position++; - buffer[position] = id; - position++; - buffer[position] = status; - position++; + int position = 0; + buffer[position] = 16; + position++; + buffer[position] = id; + position++; + buffer[position] = status; + position++; - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int writesocket) { /* - int stringsize = 3; - unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); - int position = 0; + int position = 0; - buffer[position] = 16; - position++; - buffer[position] = hitter; - position++; - buffer[position] = victim; - position++; - buffer[position] = wpnid; - position++; + buffer[position] = 16; + position++; + buffer[position] = hitter; + position++; + buffer[position] = victim; + position++; + buffer[position] = wpnid; + position++; - SendToAll(buffer, stringsize, 1, writesocket); - free(buffer); - */ + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); + */ } void SendPingList(int writesocket) { int count = onlineplayer; - int stringsize = 2 + count*3; + int stringsize = 2 + count * 3; unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); + if (buffer == NULL) + error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; - for(i = 1; i<= sv_maxplayers; i++) + for (i = 1; i <= sv_maxplayers; i++) { - if(player[i].used == 1 && player[i].joinstatus >= 4) + if (player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; - memcpy(buffer+position, &player[i].latency, 2); + memcpy(buffer + position, &player[i].latency, 2); position += 2; /* - buffer[position] = player[i].latency; - position++; - buffer[position] = 0; - position++; - */ + buffer[position] = player[i].latency; + position++; + buffer[position] = 0; + position++; + */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); } diff --git a/src/script-functions.c b/src/script-functions.c index cd121da..f238c7d 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,470 +1,492 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; - if(weapons[wpnid].special == 4 || weapons[wpnid].special == 5) + if (weapons[wpnid].special == 4 || weapons[wpnid].special == 5) { player[id].zoommode = 0; } player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnAdvancedFire(int id, int status, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnAdvancedFire(int id, int status, int writesocket) { int wpnid = player[id].slot[player[id].actualweapon].id; - switch(weapons[wpnid].special) + int temptime = mtime(); + if (temptime < player[id].zoomtimer) + { + printf("Zoomtimer error!\n"); + return 1; + } + else + { + player[id].zoomtimer = mtime() + 500; + } + + switch (weapons[wpnid].special) { case 0: printf("%s tried to hack!\n", player[id].name); - break; + return 1; case 1: case 2: { - if(status <= 1) + if (status <= 1) { player[id].zoommode = status; - return 0; + break; } - break; + return 1; } case 3: { player[id].zoommode = 1; OnFire(id, writesocket); player[id].zoommode = 0; - return 0; + break; } case 4: { - if(status <= 1) + if (status <= 1) { player[id].zoommode = status; - return 0; + break; } - break; + return 1; } case 5: { - if(status <= 2 && player[id].zoommode+1 == status) + if (status <= 2 && player[id].zoommode + 1 == status) { player[id].zoommode = status; - return 0; + break; } - else if(player[id].zoommode == 2) + else if (player[id].zoommode == 2) { player[id].zoommode = 0; - return 0; + break; } - break; + return 1; } default: { SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); + return 1; } } - return 1; + + return 0; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } - // TODO Firetimer does not work - /* - int temptime = mtime(); - printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); - if(temptime < player[id].firetimer) - { - printf("Firetimer error!"); - return 1; - } - else - { - player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; - //printf("(Debug) %d\n", player[id].firetimer); - } - */ + int temptime = mtime(); + if (temptime < player[id].firetimer) + { + printf("Firetimer error!\n"); + return 1; + } + else + { + player[id].firetimer = mtime() + + weapons[player[id].slot[player[id].actualweapon].id].freq; + } + int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if (sqrt((player[b].x - startx) * (player[b].x - startx) + (player[b].y - starty) * (player[b].y - starty)) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { if (player[id].money - weapons[wpnid].price >= 0) { int i; for (i = 0; i <= 99; i++) { - if (weapons[wpnid].freq != 0) //If weapon unknown -> everything is 0 + if (weapons[wpnid].name != NULL) //test if weapon available { - //Check if in buyzone - if (player[id].team == 1) + if (weapons[wpnid].team == 0 || weapons[wpnid].team + == player[id].team) //Check if he is in the right team to buy this weapon { - int b; - for (b = 0; b <= tspawncount; b++) + if (player[id].team == 1) { - int playerx = player[id].x; - int playery = player[id].y; - int tempx = tspawnx[b] * 32; - int tempy = tspawny[b] * 32; - //If player in buyzone (5*5) - if (playerx >= tempx - 64 && playerx <= tempx + 64 - && playery >= tempy - 64 && playery <= tempy - + 64) + //Check if in buyzone + int b; + for (b = 0; b <= tspawncount; b++) { - return 0; + int playerx = player[id].x; + int playery = player[id].y; + int tempx = tspawnx[b] * 32; + int tempy = tspawny[b] * 32; + //If player in buyzone (5*5) + if (playerx >= tempx - 64 && playerx <= tempx + 64 + && playery >= tempy - 64 && playery + <= tempy + 64) + { + return 0; + } } } - } - else if (player[id].team == 2) - { - int b; - for (b = 0; b <= ctspawncount; b++) + else if (player[id].team == 2) { - int playerx = player[id].x; - int playery = player[id].y; - int tempx = ctspawnx[b] * 32; - int tempy = ctspawny[b] * 32; - //If player in buyzone (5*5) - if (playerx >= tempx - 64 && playerx <= tempx + 64 - && playery >= tempy - 64 && playery <= tempy - + 64) + int b; + for (b = 0; b <= ctspawncount; b++) { - return 0; + int playerx = player[id].x; + int playery = player[id].y; + int tempx = ctspawnx[b] * 32; + int tempy = ctspawny[b] * 32; + //If player in buyzone (5*5) + if (playerx >= tempx - 64 && playerx <= tempx + 64 + && playery >= tempy - 64 && playery + <= tempy + 64) + { + return 0; + } } } } } } } return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } diff --git a/src/sendto_functions.c b/src/sendto_functions.c index a87f369..dad1a45 100644 --- a/src/sendto_functions.c +++ b/src/sendto_functions.c @@ -1,65 +1,77 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/sendto_functions.h" -void SendToPlayer(unsigned char *message, int length, int id, int reliable, int writesocket) +void SendToPlayer(unsigned char *message, int length, int id, int reliable, + int writesocket) { - struct sockaddr_in tempclient; - tempclient.sin_family = AF_INET; - tempclient.sin_port = player[id].port; - tempclient.sin_addr = player[id].ip; - unsigned char *buffer = malloc(length + 2); - if (buffer == NULL) error_exit("Memory error ( SendToPlayer() )"); + struct sockaddr_in tempclient; + tempclient.sin_family = AF_INET; + tempclient.sin_port = player[id].port; + tempclient.sin_addr = player[id].ip; + unsigned char *buffer = malloc(length + 2); + if (buffer == NULL) + error_exit("Memory error ( SendToPlayer() )"); - if(reliable == 1) - { - unsigned short *pNummer = &player[id].server_nummer; - memcpy(buffer, pNummer, sizeof(unsigned short)); - player[id].server_nummer += 2; - } - else if(reliable == 0) - { - player[id].server_nummer--; - unsigned short *pNummer = &player[id].server_nummer; - memcpy(buffer, pNummer, sizeof(unsigned short)); - player[id].server_nummer++; - } - memcpy(buffer+2, message, length); - udp_send(writesocket, buffer, length+2, &tempclient); + if (reliable == 1) + { + unsigned short *pNummer = &player[id].server_nummer; + memcpy(buffer, pNummer, sizeof(unsigned short)); + player[id].server_nummer += 2; + } + else if (reliable == 0) + { + player[id].server_nummer--; + unsigned short *pNummer = &player[id].server_nummer; + memcpy(buffer, pNummer, sizeof(unsigned short)); + player[id].server_nummer++; + } + memcpy(buffer + 2, message, length); + udp_send(writesocket, buffer, length + 2, &tempclient); } -void SendToAll(unsigned char *message, int length, int reliable, int writesocket) +void SendToAll(unsigned char *message, int length, int reliable, + int writesocket) { - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if(player[i].used == 1 && player[i].joinstatus >= 4) - { - SendToPlayer(message, length, i, reliable, writesocket); - } - } + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } } -void SendToTeam(unsigned char *message, int length, int reliable, int team, int writesocket) +void SendToTeam(unsigned char *message, int length, int reliable, int team, + int writesocket) { - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if(player[i].used == 1 && player[i].joinstatus >= 4 && player[i].team == team) - { - SendToPlayer(message, length, i, reliable, writesocket); - } - } + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4 && player[i].team + == team) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } } - - -void SendToAllOther(int id, unsigned char *message, int length, int reliable, int writesocket) +void SendToAllOther(int id, unsigned char *message, int length, int reliable, + int writesocket) { - int i; - for (i = 1; i <= sv_maxplayers; i++) - { - if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) - { - SendToPlayer(message, length, i, reliable, writesocket); - } - } -} \ No newline at end of file + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (player[i].used == 1 && player[i].joinstatus >= 4 && i != id) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } +} diff --git a/src/settings.c b/src/settings.c index 0db90de..71b722c 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,25 +1,33 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; unsigned char sv_name[] = "Alpha Custom CS2D Server"; unsigned char sv_map[] = "de_cs2d"; unsigned int sv_hostport = 1994; unsigned short sv_maxplayers = 32 +1; unsigned short sv_fow = 0; unsigned short sv_gamemode = 2; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; unsigned char sv_password[] = ""; unsigned short bot_count = 0; unsigned short mp_roundtime = 5; unsigned short mp_freezetime = 0; unsigned short mp_c4timer = 35; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; unsigned short mp_specmode = 1; unsigned short onlineplayer = 0; unsigned short mp_startmoney = 65000; char startweapons[] = {50, 35}; diff --git a/src/weapons.c b/src/weapons.c index 146e34b..d9d4629 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,46 +1,65 @@ +/* + * Published under GPLv3. + * For more information take a look at the Readme + * Copyright (c) by the authors of this file + * + * Author/s of this file: Jermuk + */ + #include "../include/weapons.h" -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime, short special) +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, + short wpndmg_z2, short freq, short speed, short slot, short price, + short range, short accuracy, short ammo1, short ammo2, int reloadtime, + short special, short team) { - if(name != NULL) + if (name != NULL) { - weapons[id].name = malloc(strlen(name)+1); - if(weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); - strncpy(weapons[id].name, name, strlen(name)+1); + weapons[id].name = malloc(strlen(name) + 1); + if (weapons[id].name == NULL) + error_exit("Memory Error in AddWeapon()\n"); + strncpy(weapons[id].name, name, strlen(name) + 1); } else { - weapons[id].name = NULL; + weapons[id].name = NULL; } weapons[id].weapondamage = wpndmg; weapons[id].weapondamage_z1 = wpndmg_z1; weapons[id].weapondamage_z2 = wpndmg_z2; - weapons[id].freq = freq; + if(freq != 0) + weapons[id].freq = (short)(1/freq)*60*1000; + else + weapons[id].freq = 1000; weapons[id].speed = speed; weapons[id].slot = slot; weapons[id].price = price; weapons[id].range = range; weapons[id].accuracy = accuracy; weapons[id].ammo1 = ammo1; weapons[id].ammo2 = ammo2; weapons[id].reloadtime = reloadtime; weapons[id].special = special; + weapons[id].team = team; } void WeaponInit() { int i; for(i = 0; i <= 99; i++) { - AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0); + AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0); } - AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000, 1); - AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000, 2); - AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000, 0); - AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000, 0); - AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000, 0); - AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000, 0); - AddWeapon(35, "AWP" , 50 , 65 , 150, 23 , 3, 1, 4750 , 400, 0 , 10, 30, 2000, 5); - AddWeapon(50, "Knife", 50, 100, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0, 3); + AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000, 1, 0); + AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000, 2, 0); + AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000, 0, 0); + AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000, 0, 0); + AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000, 0, 0); + AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000, 0, 0); + AddWeapon(20,"MP5" , 13 , 0, 0, 500 , 1, 1,1500, 300, 2 , 30, 120, 1000, 0, 0); + AddWeapon(21,"TMP" , 9 , 0, 0, 750 , 1, 1,1250, 100, 4 , 30, 120, 1000, 0, 2); + AddWeapon(22,"P90" , 11 , 0, 0, 750 , 1, 1,2350, 300, 3 , 50, 100, 1000, 0, 2); + AddWeapon(35, "AWP" , 50 , 65 , 150, 23 , 3, 1, 4750 , 400, 0 , 10, 30, 2000, 5, 0); + AddWeapon(50, "Knife", 50, 100, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0, 3, 0); }
Jermuk/custom_cs2dsrv
5ecab7c532ce4c1269fd6750236a7eec7bcbc18f
Fixed: - signed and unsigned warnings - unused variables All warnigns fixed under gcc!
diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe index 6586c86..8f715fb 100644 Binary files a/Release/custom_cs2dsrv.exe and b/Release/custom_cs2dsrv.exe differ diff --git a/include/functions.h b/include/functions.h index a575218..39b0d01 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,24 +1,25 @@ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(int writesocket); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); -int ValidatePaket(char *message, int id); -void PaketConfirmation(char *message, int id, int writesocket); -int CheckPlayerData(char *password); +int ValidatePaket(unsigned char *message, int id); +void PaketConfirmation(unsigned char *message, int id, int writesocket); +int CheckPlayerData(unsigned char *password); unsigned char *GetEncodedString(unsigned char *string, int length); void CheckAllPlayerForReload(int writesocket); +size_t u_strlen(unsigned char* buffer); extern time_t firsttime; #endif // FUNCTIONS_H_INCLUDED diff --git a/include/pakets.h b/include/pakets.h index 5eab215..90f302c 100644 --- a/include/pakets.h +++ b/include/pakets.h @@ -1,29 +1,30 @@ #ifndef PAKETS_H_INCLUDED #define PAKETS_H_INCLUDED #include "main.h" int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position); int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id); int ping_ingame(unsigned char *message, int length, int id, int writesocket); int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int confirmation_known(unsigned char *message, int length, int id, int writesocket); int fire(unsigned char *message, int length, int id, int writesocket); +int advanced_fire(unsigned char *message, int length, int id, int writesocket); int buy(unsigned char *message, int length, int id, int writesocket); int rotupdate(unsigned char *message, int length, int id, int writesocket); int posupdatewalk(unsigned char *message, int length, int id, int writesocket); int posupdaterun(unsigned char *message, int length, int id, int writesocket); int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket); int posrotupdaterun(unsigned char *message, int length, int id, int writesocket); int respawnrequest(unsigned char *message, int length, int id, int writesocket); int weaponchange(unsigned char *message, int length, int id, int writesocket); int teamchange(unsigned char *message, int length, int id, int writesocket); int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int specpos(unsigned char *message, int length, int id, int writesocket); int chatmessage(unsigned char *message, int length, int id, int writesocket); int joinroutine_known(unsigned char *message, int length, int id, int writesocket); int leave(int id, int writesocket); int reload(unsigned char *message, int length, int id, int writesocket); #endif // PAKETS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index 99a4061..4377645 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,24 +1,24 @@ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); void SendAdvancedFireMessage(int id, int status, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); -void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket); +void SendMessageToPlayer(int id, char *message, int status, int writesocket); void SendMessageToAll(unsigned char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); void PingAllPlayer(int writesocket, time_t firsttime); void SendReloadMessage(int id, int status, int writesocket); void SendPingList(int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/script-functions.h b/include/script-functions.h index 8fbf5aa..0c341dd 100644 --- a/include/script-functions.h +++ b/include/script-functions.h @@ -1,23 +1,24 @@ #ifndef SCRIPT_H_INCLUDED #define SCRIPT_H_INCLUDED #include "main.h" int OnJoin(int id, int writesocket); int OnLeave(int id, int writesocket); int OnSpecmove(int id, int newx, int newy, int writesocket); int OnServerStart(); int OnExit(); int OnRespawnRequest(int id, int writesocket); int OnRespawn(int id, int writesocket); int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); int OnAdvancedFire(int id, int status, int writesocket); int OnFire(int id, int writesocket); int OnHit(int hitter, int victim, int writesocket); int OnBuyAttempt(int id, int wpnid, int writesocket); +int OnBuy(int id, int wpnid, int writesocket); int OnKill(int hitter, int victim, int wpnid, int writesocket); int OnChatMessage(int id, unsigned char *message, int team, int writesocket); int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket); int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket); int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket); #endif diff --git a/include/structs.h b/include/structs.h index 1a6c27d..4bdc09f 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,87 +1,88 @@ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; float freq; short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; short special; }; struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; short special; }; /* * special * 0 = Normal * 1 = Silencer * 2 = Burst * 3 = Melee * 4 = 1xZoom * 5 = 2xZoom * 6 = Shotgun */ struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; time_t lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; - short deaths, score; + unsigned short deaths; + short score; unsigned short x,y; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; unsigned short kills; int reloadtimer, reloading; short dead; int start; unsigned short latency; int firetimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/src/cross_layer.c b/src/cross_layer.c index 3fdf7e5..8be62e4 100644 --- a/src/cross_layer.c +++ b/src/cross_layer.c @@ -1,191 +1,191 @@ #include "../include/cross_layer.h" /** * \fn int create_socket(void) * \brief creates a socket * \return socketnumber or 0 if failed */ int create_socket(void) { #ifdef _WIN32 WSADATA wsa; if (WSAStartup (MAKEWORD(2,0), &wsa) != 0) { error_exit("WSAStartup() failed"); } else { int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { error_exit("socket() failed"); } return sock; } #else const int y = 1; int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { error_exit("socket() failed"); } setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); return sock; #endif return 0; } /** * \fn int bind_socket(int *sock, unsigned long adress, unsigned short port) * \brief bind a socket to a specific IP and port * \param *sock socket to bind * \param adress ip-address to bind * \param port port to bind */ void bind_socket(int *sock, unsigned long adress, unsigned short port) { #ifdef _WIN32 struct sockaddr_in server; memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) { error_exit("bind() failed"); } #else struct sockaddr_in server; memset(&server, 0, sizeof (server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) { error_exit("bind() failed"); } #endif } /** * \fn int error_exit(char *message) * \brief Show a error message and exit the programm * \param *message message to display */ void error_exit(char *message) { printf("%s", message); /* printf("%s: %d\n", message, WSAGetLastError()); //debug(stderr); #else printf("%s: %s\n", message, strerror(errno)); //debug(stderr); */ exit(EXIT_FAILURE); } /** * \fn cleanup(void) * \brief clean the socket */ void cleanup(void) { OnExit(); #ifdef _WIN32 WSACleanup(); #else /* Nichts zu tun */ #endif } /** * \fn mtime(void) * \brief return the actually time in miliseconds for win and linux * \return time in ms */ int mtime(void) { #ifdef _WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv,NULL); return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); #endif } /** * \fn void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief send a message over a specific socket to a client * \param *socket socket to send over * \param *data data to send * \param length size of *data * \param *client sockaddr_in struct to send data to */ void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) { int rc; //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); - rc = sendto(socket, data, length, 0, (struct sockaddr *)client, sizeof(*client)); + rc = sendto(socket, (char*)data, length, 0, (struct sockaddr *)client, sizeof(*client)); /* int i; for(i = 0; i <= length; i++) { printf("%d-", data[i]); } printf("\n"); */ #ifdef _WIN32 if (rc == SOCKET_ERROR) error_exit("sendto() failed"); #else if (rc < 0) error_exit("sendto() failed"); #endif //else //printf("Message sent!\n"); } /** * \fn int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) * \brief Recieves a message on a specicific socket and save (if something recieved) the data * \param socket socket to recieve * \param *data pointer where the data should be saved * \param length max length of *data * \param *client pointer where the clientdata (ip, ...) should be saved * \return length of read data */ int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) { struct sockaddr_in newclient; - unsigned int len; + int len; int size; len = sizeof(struct sockaddr_in); - size = recvfrom(socket, data, length, 0, (struct sockaddr *)&newclient,&len); + size = recvfrom(socket, (char*)data, length, 0, (struct sockaddr *)&newclient,&len); *client = newclient; #ifdef _WIN32 if (size == SOCKET_ERROR) { error_exit("recvfrom() failed"); } #else if (size < 0) { error_exit("recvfrom() failed"); } #endif else { return size; } return 0; } diff --git a/src/functions.c b/src/functions.c index ac026e4..8c77461 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,416 +1,421 @@ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * */ int PlayerTimeout(int id) { //id = 0; time_t actualtime; time(&actualtime); if(((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket != 0) { return 1; } return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; - if(strcmp(sv_password, "")) + if(strcmp((char*)sv_password, "")) { serverstatus += 1; } if(sv_usgnonly == 1) { serverstatus += 2; } if(sv_fow == 1) { serverstatus += 4; } if(sv_friendlyfire == 1) { serverstatus += 8; } if(1) //Same Version? { serverstatus += 16; } if(sv_gamemode != 0) { serverstatus += 32; } if(0) //LuaScripts { serverstatus += 64; } if(1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x>>8) | (*x<<8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ -int ValidatePaket(char *message, int id) +int ValidatePaket(unsigned char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 != 0) { if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if(*pTempNummer-1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ -void PaketConfirmation(char *message, int id, int writesocket) +void PaketConfirmation(unsigned char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer+1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ -int CheckPlayerData(char *password) +int CheckPlayerData(unsigned char *password) { - if(strcmp(sv_password, password) != 0) + if( strcmp((char*)sv_password, (char*)password) != 0 ) { printf("Password wrong!\n"); return 1; } if(sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length+1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(int writesocket) * \brief check all player if their reload is ended, * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].reloading != 0) { if(player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if(player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } + +size_t u_strlen(unsigned char* buffer) +{ + return strlen((char*)buffer); +} diff --git a/src/map.c b/src/map.c index 77afadd..1fcb516 100644 --- a/src/map.c +++ b/src/map.c @@ -1,206 +1,206 @@ #include "../include/map.h" /** * \fn void ReadMap() * \brief reads the map and put all needed information into a variable * needed: tspawn and ctspawn */ void ReadMap() { FILE *file; int i; tspawncount = 0; ctspawncount = 0; - char *mappath = malloc(strlen(sv_map) + 5); - memcpy(mappath, sv_map, strlen(sv_map)); - memcpy(mappath + strlen(sv_map), ".map\0", 5); + char *mappath = malloc(u_strlen(sv_map) + 5); + memcpy(mappath, sv_map, u_strlen(sv_map)); + memcpy(mappath + u_strlen(sv_map), ".map\0", 5); file = fopen(mappath, "rb"); if (file == NULL) error_exit("Map not found.. Abort\n"); else printf("Loading '%s'..", mappath); free(mappath); //------------------------------ unsigned char *mapheader = ReadLine(file); for (i = 1; i <= 9; i++) ReadByte(file); for (i = 1; i <= 10; i++) ReadInt(file); for (i = 1; i <= 10; i++) ReadLine(file); unsigned char *code = ReadLine(file); unsigned char *tileset = ReadLine(file); unsigned char loaded = ReadByte(file); int maxx = ReadInt(file); int maxy = ReadInt(file); unsigned char *background = ReadLine(file); - int backgroundx = ReadInt(file); - int backgroundy = ReadInt(file); - unsigned char red = ReadByte(file); - unsigned char green = ReadByte(file); - unsigned char blue = ReadByte(file); + /*int backgroundx =*/ ReadInt(file); //avoid warnings: unused variable + /*int backgroundy =*/ ReadInt(file); + /*unsigned char red =*/ ReadByte(file); + /*unsigned char green =*/ ReadByte(file); + /*unsigned char blue =*/ ReadByte(file); unsigned char *mapcheck = ReadLine(file); //----------------------------------------- unsigned char *tilemode = malloc(loaded + 1); if (tilemode == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= loaded; i++) { tilemode[i] = ReadByte(file); } map = malloc(maxx * sizeof(struct TILE *)); if (map == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= maxx; i++) { map[i] = malloc(maxy * sizeof(struct TILE *)); if (map[i] == NULL) error_exit("Memory error in ReadMap()\n"); int b; for (b = 0; b <= maxy; b++) { unsigned char bytecache = ReadByte(file); if (bytecache > loaded) { bytecache = 0; } map[i][b].tileid = bytecache; map[i][b].mode = tilemode[bytecache]; //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); } } //--------------------------------------- unsigned char enities_count = ReadByte(file); for (i = 0; i <= enities_count - 1; i++) { unsigned char *name = ReadLine(file); unsigned char typ = ReadByte(file); int x = ReadInt(file); int y = ReadInt(file); unsigned char *trigger = ReadLine(file); //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); int b; for (b = 0; b <= 9; b++) { - int unknownint = ReadInt(file); + /*int unknownint =*/ ReadInt(file); unsigned char *unknown = ReadLine(file); //eprintf("(%d) %s || ", unknownint, unknown); free(unknown); } switch (typ) { case 0: { tspawnx[tspawncount] = x; tspawny[tspawncount] = y; tspawncount++; break; } case 1: { ctspawnx[ctspawncount] = x; ctspawny[ctspawncount] = y; ctspawncount++; break; } default: { break; } } free(name); free(trigger); } fclose(file); eprintf("loaded!\n"); free(mapheader); free(code); free(tileset); free(background); free(mapcheck); } /** * \fn unsigned char *ReadLine(FILE *file) * \brief read from a file stream a cs2d line (ends with \r\n; windows end) * \param *file the file stream * \return a pointer to the read line */ unsigned char *ReadLine(FILE *file) { int position = 0; char *line = NULL; char c; while ((c = fgetc(file)) != 13) { if (c == EOF) error_exit("EndOfFile in ReadByte()\n"); line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = c; position++; } line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = '\0'; position++; fgetc(file); //0x0A - return line; + return (unsigned char*)line; } /** * \fn unsigned char ReadByte(FILE *file) * \brief read from a file stream a byte * \param *file the file stream * \return the read byte */ unsigned char ReadByte(FILE *file) { unsigned char byte = fgetc(file); if (byte == EOF) error_exit("EndOfFile in ReadByte()\n"); return byte; } /** * \fn int ReadInt(FILE *file) * \brief read from a file stream a integer * \param *file the file stream * \return the read integer */ int ReadInt(FILE *file) { unsigned char byte1 = fgetc(file); if (byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte2 = fgetc(file); if (byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte3 = fgetc(file); if (byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte4 = fgetc(file); if (byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/pakets.c b/src/pakets.c index 8c4d94d..8407716 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -86,1566 +86,1566 @@ int ping_ingame(unsigned char *message, int length, int id, int writesocket) printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; //printf("%s: %d\n", player[id].name, player[id].latency); return paketlength; } /** * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a confirmation for unknown player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } /** * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) * \brief handles a confirmation for known player * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } /** * \fn int fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a fire * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch(OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } /** * \fn int advanced_fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a advanced_fire (right click) * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int advanced_fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if(length < paketlength) { printf("Invalid packet (advanced_fire)!\n"); return length; } unsigned int status = message[1]; switch(OnAdvancedFire(id, status, writesocket)) { case 0: SendAdvancedFireMessage(id, status, writesocket); break; case 1: break; } return paketlength; } /** * \fn int buy(unsigned char *message, int length, int id, int writesocket) * \brief handles a buy request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnBuyAttempt(id, wpnid, writesocket)) { case 0: OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } /** * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) * \brief handles a rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if(length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message+1, sizeof(float)); if(temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } /** * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) * \brief handles a position walk update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } /** * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) * \brief handles a position run update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } /** * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position walk and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position run and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) * \brief handles a respawn request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch(OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch(player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp]+0.5)*32; player[id].y = (tspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp]+0.5)*32; player[id].y = (ctspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } /** * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a weapon change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch(OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if(skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param *client pointer to the client information structure * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer+2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if(length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ - int stringsize = 10 + strlen(sv_name) + strlen(sv_map); + int stringsize = 10 + u_strlen(sv_name) + u_strlen(sv_map); if(sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch(message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; - buffer[position] = strlen(sv_name); + buffer[position] = u_strlen(sv_name); position++; - memcpy(buffer+position, sv_name, strlen(sv_name)); - position += strlen(sv_name); - buffer[position] = strlen(sv_map); + memcpy(buffer+position, sv_name, u_strlen(sv_name)); + position += u_strlen(sv_name); + buffer[position] = u_strlen(sv_map); position++; - memcpy(buffer+position, sv_map, strlen(sv_map)); - position += strlen(sv_map); + memcpy(buffer+position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if(sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if(length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch(message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS-1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } - int stringsize = 5 + strlen(pre_authcode); + int stringsize = 5 + u_strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; - buffer[position] = strlen(pre_authcode); + buffer[position] = u_strlen(pre_authcode); position++; - memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); + memcpy(buffer+position, pre_authcode, u_strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if(paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch(OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength=4; unsigned char team, unknown; int paketsize; if(paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length-position+1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(string, message+position, paketsize); string[paketsize] = '\0'; position += paketsize; switch(OnChatMessage(id, string, team, writesocket)) { case 0: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch(message[1]) { case 0: { paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if(player[id].joinstatus == 1) { paketlength = 16; // ??? if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; player[id].name = malloc(stringsize); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message+position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; unsigned char *password = malloc(stringsize); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message+position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; - for (i = 0; i <= strlen(password); i++) + for (i = 0; i <= u_strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; unsigned char *encryption1 = malloc(stringsize); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message+position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message+position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes /* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif */ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; player[id].spraylogo = malloc(stringsize); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message+position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; unsigned char *maphash= malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message+position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; player[id].win= malloc(stringsize); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message+position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; - //printf("\tWIN: %s (%d)\n", player[id].win, strlen(player[id].win)); + //printf("\tWIN: %s (%d)\n", player[id].win, u_strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch(tempstatus) { case 0x00: - stringsize = 6 + strlen(sv_map) + strlen(pre_authcode); + stringsize = 6 + u_strlen(sv_map) + u_strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; - buffer[position] = strlen(sv_map); + buffer[position] = u_strlen(sv_map); position++; - memcpy(buffer+position, sv_map, strlen(sv_map)); - position += strlen(sv_map); - buffer[position] = strlen(pre_authcode); + memcpy(buffer+position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); + buffer[position] = u_strlen(pre_authcode); position++; - memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); - position += strlen(pre_authcode); + memcpy(buffer+position, pre_authcode, u_strlen(pre_authcode)); + position += u_strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } - //stringsize = 16 + strlen(sv_map); + //stringsize = 16 + u_strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if(stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if(player[id].joinstatus == 2) { int position = 2; paketlength = 5; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Map-Hash too big\n"); return length; } position++; unsigned char *maphash = malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message+position, stringsize); maphash[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMaphash: %s\n", maphash); //pre_authcode_respond stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("pre_authcon_respond too big\n"); return length; } position++; unsigned char *pre_authcode_respond = malloc(stringsize); if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(pre_authcode_respond, message+position, stringsize); pre_authcode_respond[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); //Player Version - unsigned char mapstatus = message[position]; //avoid warning + //unsigned char mapstatus = message[position]; //avoid warning position++; //printf("\tMapstatus: %d\n", mapstatus); free(pre_authcode_respond); free(maphash); //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if(player[id].joinstatus == 3) { int position = 2; paketlength = 3; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Mapname too big\n"); return length; } position++; unsigned char *mapname = malloc(stringsize); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message+position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- - stringsize = 28 + strlen(sv_map) + strlen(sv_name); + stringsize = 28 + u_strlen(sv_map) + u_strlen(sv_name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; - buffer[position] = strlen(sv_map); + buffer[position] = u_strlen(sv_map); position++; - memcpy(buffer+position, sv_map, strlen(sv_map)); - position += strlen(sv_map); + memcpy(buffer+position, sv_map, u_strlen(sv_map)); + position += u_strlen(sv_map); - buffer[position] = strlen(sv_name); + buffer[position] = u_strlen(sv_name); position++; - memcpy(buffer+position, sv_name, strlen(sv_name)); - position += strlen(sv_name); + memcpy(buffer+position, sv_name, u_strlen(sv_name)); + position += u_strlen(sv_name); buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_friendlyfire; position++; buffer[position] = 0; //Unknown position++; buffer[position] = mp_roundtime; position++; buffer[position] = mp_freezetime; position++; buffer[position] = mp_c4timer; position++; buffer[position] = 32; //Unknown position++; buffer[position] = 124; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 1; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_maxplayers; position++; buffer[position] = sv_fow; position++; buffer[position] = mp_specmode; position++; buffer[position] = sv_gamemode; position++; buffer[position] = mp_respawndelay; position++; buffer[position] = mp_infammo; position++; - buffer[position] = 3; //strlen ACK + buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; position++; buffer[position] = onlineplayer; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 1 && i != id) { unsigned char *encodedname; - encodedname = GetEncodedString(player[i].name, strlen(player[i].name)); + encodedname = GetEncodedString(player[i].name, u_strlen(player[i].name)); unsigned short *deaths = &player[i].deaths; - unsigned short tempscore = player[i].deaths + 1000; + unsigned short tempscore = (unsigned)(player[i].deaths + 1000); unsigned short *score = &tempscore; unsigned short tempx = (player[i].x); unsigned short tempy = (player[i].y); unsigned short *x = &tempx; unsigned short *y = &tempy; float *ptemprotation = &player[i].rotation; - int playersize = 25 + strlen(encodedname); + int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = i; position++; - buffer[position] = strlen(encodedname); + buffer[position] = u_strlen(encodedname); position++; - memcpy(buffer+position, encodedname, strlen(encodedname)); - position += strlen(encodedname); + memcpy(buffer+position, encodedname, u_strlen(encodedname)); + position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[i].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; /* buffer[position] = score[0]; //Deaths position++; buffer[position] = score[1]; //Deaths position++; */ memcpy(buffer+position, score, 2); position += 2; /* buffer[position] = deaths[0]; //Deaths position++; buffer[position] = deaths[1]; //Deaths position++; */ memcpy(buffer+position, deaths, 2); position += 2; memcpy(buffer+position, x, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; memcpy(buffer+position, y, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = ptemprotation[0]; //Rotation position++; buffer[position] = ptemprotation[1]; //Rotation position++; buffer[position] = player[i].health; //Health position++; buffer[position] = player[i].armor; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe position++; buffer[position] = 0; //Unknown position++; /* 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 e8 03 00 00 12 01 00 00 01 03 e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 */ } } if(1) { unsigned char *encodedname; - encodedname = GetEncodedString(player[id].name, strlen(player[id].name)); + encodedname = GetEncodedString(player[id].name, u_strlen(player[id].name)); - int playersize = 25 + strlen(encodedname); + int playersize = 25 + u_strlen(encodedname); buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = id; position++; - buffer[position] = strlen(encodedname); + buffer[position] = u_strlen(encodedname); position++; - memcpy(buffer+position, encodedname, strlen(encodedname)); - position += strlen(encodedname); + memcpy(buffer+position, encodedname, u_strlen(encodedname)); + position += u_strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[id].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 232; //Unknown position++; buffer[position] = 3; //Unknown position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //X position++; buffer[position] = 0; //X position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Health position++; buffer[position] = 0; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Aktuelle Waffe 50 = Knife position++; buffer[position] = 0; //Unknown position++; } SendToPlayer(buffer, position, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- HostageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 2; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ItemData ----------- /* fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 */ stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 3; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- EnityData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 4; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 5; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ProjectileData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 6; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectImageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 7; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- Final ACK ----------- stringsize = 7; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 200; //third payload position++; - buffer[position] = 3; //strlen ACK + buffer[position] = 3; //u_strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); player[id].joinstatus = 4; free(mapname); OnJoin(id, writesocket); } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } default: { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } return paketlength; } int leave(int id, int writesocket) { OnLeave(id, writesocket); free(player[id].name); free(player[id].usgn); free(player[id].spraylogo); free(player[id].win); player[id].name = NULL; player[id].usgn = NULL; player[id].spraylogo = NULL; player[id].win = NULL; onlineplayer--; ClearPlayer(id); return 2; } int reload(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if(length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int status; status = message[position]; position++; if(status == 1) { SendReloadMessage(id, 1, writesocket); player[id].reloading = player[id].actualweapon; player[id].reloadtimer = mtime()+weapons[player[id].slot[player[id].actualweapon].id].reloadtime; } return paketlength; } diff --git a/src/respond_messages.c b/src/respond_messages.c index 342cee8..32f040f 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,595 +1,595 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendAdvancedFireMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 8; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer+position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } -void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) +void SendMessageToPlayer(int id, char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ - int stringsize = 5 + strlen(message); + int stringsize = 5 + u_strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; - buffer[position] = strlen(message); + buffer[position] = u_strlen(message); position++; buffer[position] = 0; position++; - memcpy(buffer+position, message, strlen(message)); - position += strlen(message); + memcpy(buffer+position, message, u_strlen(message)); + position += u_strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { - int stringsize = 4 + strlen(player[id].name); + int stringsize = 4 + u_strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; - buffer[position] = strlen(player[id].name); + buffer[position] = u_strlen(player[id].name); position++; - memcpy(buffer+position, player[id].name, strlen(player[id].name)); - position += strlen(player[id].name); + memcpy(buffer+position, player[id].name, u_strlen(player[id].name)); + position += u_strlen(player[id].name); - buffer[position] = 0; //strlen ACK + buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; - buffer[position] = 0; //strlen ACK + buffer[position] = 0; //u_strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { - int stringsize = 5 + strlen(message); + int stringsize = 5 + u_strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; - buffer[position] = strlen(message); + buffer[position] = u_strlen(message); position++; buffer[position] = 0; position++; - memcpy(buffer+position, message, strlen(message)); - position += strlen(message); + memcpy(buffer+position, message, u_strlen(message)); + position += u_strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket, time_t firsttime) { time_t actualtime; time(&actualtime); if(1 == 2)//if(actualtime >= (firsttime + 5)) //FIXME will be executed many many times per sec { firsttime = actualtime; SendPingList(writesocket); //SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int writesocket) { /* int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = hitter; position++; buffer[position] = victim; position++; buffer[position] = wpnid; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); */ } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count*3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for(i = 1; i<= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer+position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); }
Jermuk/custom_cs2dsrv
96f6bdefbc7de9865596b4f85f5a074164e8f906
Added: - Advanced fire support (means silencer, zoom, ...) Found Bugs: - PingAllPlayer: marked "if" don't work
diff --git a/include/main.h b/include/main.h index f4acaa2..963a0b4 100644 --- a/include/main.h +++ b/include/main.h @@ -1,44 +1,43 @@ #ifndef MAIN_H_INCLUDED #define MAIN_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdarg.h> //log.h #include <math.h> //aim #define PI 3.14159265 #ifdef _WIN32 #include <winsock.h> #include <io.h> #else #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/select.h> //for select() #endif /* Self-made includes */ #include "log.h" #include "settings.h" #include "structs.h" #include "weapons.h" #include "cross_layer.h" #include "functions.h" #include "sendto_functions.h" #include "respond_messages.h" #include "pakets.h" #include "script-functions.h" #include "map.h" int main(); - #endif // MAIN_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index 6d387d9..99a4061 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,23 +1,24 @@ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); +void SendAdvancedFireMessage(int id, int status, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket); void SendMessageToAll(unsigned char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); void PingAllPlayer(int writesocket, time_t firsttime); void SendReloadMessage(int id, int status, int writesocket); void SendPingList(int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/script-functions.h b/include/script-functions.h index 06622d9..8fbf5aa 100644 --- a/include/script-functions.h +++ b/include/script-functions.h @@ -1,22 +1,23 @@ #ifndef SCRIPT_H_INCLUDED #define SCRIPT_H_INCLUDED #include "main.h" int OnJoin(int id, int writesocket); int OnLeave(int id, int writesocket); int OnSpecmove(int id, int newx, int newy, int writesocket); int OnServerStart(); int OnExit(); int OnRespawnRequest(int id, int writesocket); int OnRespawn(int id, int writesocket); int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); +int OnAdvancedFire(int id, int status, int writesocket); int OnFire(int id, int writesocket); int OnHit(int hitter, int victim, int writesocket); int OnBuyAttempt(int id, int wpnid, int writesocket); int OnKill(int hitter, int victim, int wpnid, int writesocket); int OnChatMessage(int id, unsigned char *message, int team, int writesocket); int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket); int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket); int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket); #endif diff --git a/include/settings.h b/include/settings.h index 9fa6128..2f8316f 100644 --- a/include/settings.h +++ b/include/settings.h @@ -1,36 +1,36 @@ #ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #define MAX_BUF 1024 /* --- Server Settings --- */ #define LOCAL_PORT 1994 #define MAX_CLIENTS 64 #define TIMEOUT 10 extern unsigned char pre_authcode[]; extern unsigned char sv_name[]; extern unsigned char sv_map[]; extern unsigned int sv_hostport; extern unsigned short sv_maxplayers; extern unsigned short sv_fow; extern unsigned short sv_gamemode; extern unsigned short sv_friendlyfire; extern unsigned short sv_usgnonly; extern unsigned char sv_password[]; extern unsigned short bot_count; extern unsigned short mp_roundtime; extern unsigned short mp_freezetime; extern unsigned short mp_c4timer; extern unsigned short mp_infammo; extern unsigned short mp_respawndelay; extern unsigned short mp_specmode; extern unsigned short onlineplayer; extern unsigned short mp_startmoney; -#define STARTWEAPONS_COUNT 1 +#define STARTWEAPONS_COUNT 2 extern char startweapons[]; #endif // SETTINGS_H_INCLUDED diff --git a/include/structs.h b/include/structs.h index d2a6b78..1a6c27d 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,75 +1,87 @@ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; float freq; short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; + short special; }; struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; + short special; }; +/* + * special + * 0 = Normal + * 1 = Silencer + * 2 = Burst + * 3 = Melee + * 4 = 1xZoom + * 5 = 2xZoom + * 6 = Shotgun + */ struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; time_t lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; short deaths, score; unsigned short x,y; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; unsigned short kills; int reloadtimer, reloading; short dead; int start; unsigned short latency; int firetimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/include/weapons.h b/include/weapons.h index c305899..e6fc713 100644 --- a/include/weapons.h +++ b/include/weapons.h @@ -1,10 +1,10 @@ #ifndef WEAPONS_H_INCLUDED #define WEAPONS_H_INCLUDED #include "main.h" -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime); +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime, short special); void WeaponInit(); struct WEAPON weapons[100]; #endif // WEAPONS_H_INCLUDED diff --git a/src/main.c b/src/main.c index 1d61ff8..cda2985 100644 --- a/src/main.c +++ b/src/main.c @@ -1,251 +1,254 @@ /* * Published under GPL v3 * Copyright by DÖNARMASTER aka Jermuk and <www.Kebab-Clan.de> * * Alpha 0.1 * * If you want to help me or you have questions * contact me via PM (Jermuk) or E-Mail <[email protected]> */ #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); while (1) { CheckForTimeout(readsocket); PingAllPlayer(readsocket, firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); select(readsocket + 1, &descriptor, NULL, NULL, NULL); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; + case 8: + rtn = advanced_fire(message, tempsize, id, readsocket); + break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return EXIT_SUCCESS; } diff --git a/src/pakets.c b/src/pakets.c index 5cd2de0..8c4d94d 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -1,674 +1,704 @@ #include "../include/pakets.h" /** * \fn int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) * \brief every unknown packet lands here * \param *message pointer to the unknown message * \param length sizeof message * \param *buffer pointer to the udp-packet * \param size sizeof buffer * \param position where the unknown message in buffer begins * \return read bytes (specific: parameter length) */ int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) { int paketlength = length; int i; printf("Unknown packet: "); for(i = 2; i <= position-1; i++) { eprintf("%d-", buffer[i]); } eprintf("\n\t"); for(i = 0; i <= length-1; i++) { eprintf("%d-", message[i]); } eprintf("\n"); return paketlength; } /** * \fn int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a connection setup for unknown player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_unknown)!\n"); return length; } return paketlength; } /** * \fn int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a connection setup for known player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_known)!\n"); return length; } return paketlength; } /** * \fn int ping_ingame(unsigned char *message, int length, int id, int writesocket) * \brief handles a answer from the server ingame ping. this function calculates the latency * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_ingame(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; //printf("%s: %d\n", player[id].name, player[id].latency); return paketlength; } /** * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) * \brief handles a confirmation for unknown player * \param *message pointer to the unknown message * \param length sizeof message * \param ip clients ip * \param port clients port * \return read bytes (specific: 3) */ int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } /** * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) * \brief handles a confirmation for known player * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } /** * \fn int fire(unsigned char *message, int length, int id, int writesocket) * \brief handles a fire * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch(OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } +/** + * \fn int advanced_fire(unsigned char *message, int length, int id, int writesocket) + * \brief handles a advanced_fire (right click) + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 1) + */ +int advanced_fire(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 2; + if(length < paketlength) + { + printf("Invalid packet (advanced_fire)!\n"); + return length; + } + unsigned int status = message[1]; + + switch(OnAdvancedFire(id, status, writesocket)) + { + case 0: + SendAdvancedFireMessage(id, status, writesocket); + break; + case 1: + break; + } + return paketlength; +} + /** * \fn int buy(unsigned char *message, int length, int id, int writesocket) * \brief handles a buy request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnBuyAttempt(id, wpnid, writesocket)) { case 0: OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } /** * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) * \brief handles a rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if(length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message+1, sizeof(float)); if(temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } /** * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) * \brief handles a position walk update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } /** * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) * \brief handles a position run update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } /** * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position walk and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) * \brief handles a position run and rotation update * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 9) */ int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } /** * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) * \brief handles a respawn request * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 1) */ int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch(OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch(player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp]+0.5)*32; player[id].y = (tspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp]+0.5)*32; player[id].y = (ctspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } /** * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a weapon change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param id clients player id * \param writesocket the socket where it was read * \return read bytes (specific: 3) */ int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch(OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if(skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } /** * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) * \brief handles a team change * \param *message pointer to the message * \param length sizeof message * \param *client pointer to the client information structure * \param writesocket the socket where it was read * \return read bytes (specific: 5) */ int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer+2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if(length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + strlen(sv_name) + strlen(sv_map); if(sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch(message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if(sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if(length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch(message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS-1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; diff --git a/src/respond_messages.c b/src/respond_messages.c index 82bdfe2..342cee8 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,574 +1,595 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } +void SendAdvancedFireMessage(int id, int status, int writesocket) +{ + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); + + int position = 0; + + buffer[position] = 8; + position++; + buffer[position] = id; + position++; + buffer[position] = status; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer+position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = strlen(player[id].name); position++; memcpy(buffer+position, player[id].name, strlen(player[id].name)); position += strlen(player[id].name); buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket, time_t firsttime) { time_t actualtime; time(&actualtime); - if(actualtime >= (firsttime + 5)) + if(1 == 2)//if(actualtime >= (firsttime + 5)) //FIXME will be executed many many times per sec { firsttime = actualtime; SendPingList(writesocket); - SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status + + //SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int writesocket) { /* int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = hitter; position++; buffer[position] = victim; position++; buffer[position] = wpnid; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); */ } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count*3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for(i = 1; i<= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer+position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); } diff --git a/src/script-functions.c b/src/script-functions.c index 5bab55b..cd121da 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,403 +1,470 @@ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if (player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for (i = 0; i <= 9; i++) { if (player[id].slot[i].id == wpnid) { player[id].actualweapon = i; - player[id].zoommode = 0; //CHANGE there are also silencer, ... + if(weapons[wpnid].special == 4 || weapons[wpnid].special == 5) + { + player[id].zoommode = 0; + } player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } +/* + int OnAdvancedFire(int id, int status, int writesocket) + Return Values: + 0 - OK + 1 - Not OK + */ +int OnAdvancedFire(int id, int status, int writesocket) +{ + int wpnid = player[id].slot[player[id].actualweapon].id; + + switch(weapons[wpnid].special) + { + case 0: + printf("%s tried to hack!\n", player[id].name); + break; + case 1: + case 2: + { + if(status <= 1) + { + player[id].zoommode = status; + return 0; + } + break; + } + case 3: + { + player[id].zoommode = 1; + OnFire(id, writesocket); + player[id].zoommode = 0; + return 0; + } + case 4: + { + if(status <= 1) + { + player[id].zoommode = status; + return 0; + } + break; + } + case 5: + { + if(status <= 2 && player[id].zoommode+1 == status) + { + player[id].zoommode = status; + return 0; + } + else if(player[id].zoommode == 2) + { + player[id].zoommode = 0; + return 0; + } + break; + } + default: + { + SendMessageToPlayer(id, "Not implemented yet!", 1, writesocket); + } + + } + return 1; +} /* int OnFire(int id, int writesocket) Return Values: 0 - OK + 1 - Not OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if (*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if (*ammo1 != -1) { *ammo1 = *ammo1 - 1; } } // TODO Firetimer does not work /* int temptime = mtime(); printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); if(temptime < player[id].firetimer) { printf("Firetimer error!"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; //printf("(Debug) %d\n", player[id].firetimer); } */ int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = { 0 }; if (temprot < 0) { temprot = 360 - (temprot * -1); } temprot = 360 - temprot; temprot += 90; if (temprot > 360) { temprot = temprot - 360; } rotx = cos((temprot) * PI / 180); roty = sin((temprot) * PI / 180); for (i = 1; i <= range; i++) { startx += i * rotx; starty -= i * roty; int tilex = (int) (startx) / 32; int tiley = (int) (starty) / 32; if (tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if (tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for (b = 1; b <= sv_maxplayers; b++) { if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if (sqrt((player[b].x - startx) * (player[b].x - startx) + (player[b].y - starty) * (player[b].y - starty)) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch (player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if (player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { if (player[id].money - weapons[wpnid].price >= 0) { int i; for (i = 0; i <= 99; i++) { if (weapons[wpnid].freq != 0) //If weapon unknown -> everything is 0 { //Check if in buyzone if (player[id].team == 1) { int b; for (b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b] * 32; int tempy = tspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { return 0; } } } else if (player[id].team == 2) { int b; for (b = 0; b <= ctspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = ctspawnx[b] * 32; int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) if (playerx >= tempx - 64 && playerx <= tempx + 64 && playery >= tempy - 64 && playery <= tempy + 64) { return 0; } } } } } } return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if (team == 1) { printf("%s: %s\n", player[id].name, message); } else if (team == 2) { printf("%s (Team): %s\n", player[id].name, message); } SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if (skin != 5) { switch (team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } SendHitMessage(id, id, 0, writesocket); player[id].dead = 1; RemoveAllPlayerWeapon(id); } if (team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } diff --git a/src/settings.c b/src/settings.c index a71bb4b..0db90de 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,25 +1,25 @@ #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; unsigned char sv_name[] = "Alpha Custom CS2D Server"; unsigned char sv_map[] = "de_cs2d"; unsigned int sv_hostport = 1994; unsigned short sv_maxplayers = 32 +1; unsigned short sv_fow = 0; unsigned short sv_gamemode = 2; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; unsigned char sv_password[] = ""; unsigned short bot_count = 0; unsigned short mp_roundtime = 5; unsigned short mp_freezetime = 0; unsigned short mp_c4timer = 35; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; unsigned short mp_specmode = 1; unsigned short onlineplayer = 0; unsigned short mp_startmoney = 65000; -char startweapons[] = {50}; +char startweapons[] = {50, 35}; diff --git a/src/weapons.c b/src/weapons.c index deedd50..146e34b 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,44 +1,46 @@ #include "../include/weapons.h" -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime) +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime, short special) { if(name != NULL) { weapons[id].name = malloc(strlen(name)+1); if(weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); strncpy(weapons[id].name, name, strlen(name)+1); } else { weapons[id].name = NULL; } weapons[id].weapondamage = wpndmg; weapons[id].weapondamage_z1 = wpndmg_z1; weapons[id].weapondamage_z2 = wpndmg_z2; weapons[id].freq = freq; weapons[id].speed = speed; weapons[id].slot = slot; weapons[id].price = price; weapons[id].range = range; weapons[id].accuracy = accuracy; weapons[id].ammo1 = ammo1; weapons[id].ammo2 = ammo2; weapons[id].reloadtime = reloadtime; + weapons[id].special = special; } void WeaponInit() { int i; for(i = 0; i <= 99; i++) { - AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0); + AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0); } - AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000); - AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000); - AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000); - AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000); - AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000); - AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000); - AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0); + AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000, 1); + AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000, 2); + AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000, 0); + AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000, 0); + AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000, 0); + AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000, 0); + AddWeapon(35, "AWP" , 50 , 65 , 150, 23 , 3, 1, 4750 , 400, 0 , 10, 30, 2000, 5); + AddWeapon(50, "Knife", 50, 100, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0, 3); }
Jermuk/custom_cs2dsrv
8fcad5de6c31bf05161d07f2b2884818939c63a1
First public release - Added message every 5 seconds - license now GPLv3
diff --git a/src/main.c b/src/main.c index db78a12..1d61ff8 100644 --- a/src/main.c +++ b/src/main.c @@ -1,241 +1,251 @@ +/* + * Published under GPL v3 + * Copyright by DÖNARMASTER aka Jermuk and <www.Kebab-Clan.de> + * + * Alpha 0.1 + * + * If you want to help me or you have questions + * contact me via PM (Jermuk) or E-Mail <[email protected]> + */ + #include "../include/main.h" /** * \fn int main() * \brief initialize sockets and if a message was recieved, give it to the right function. * \return EXIT_SUCCESS or EXIT_FAILURE */ int main() { /** * Initalize variables, weapons, players and sockets */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); /** * \var needed for PingAllPlayer() to execute it every 5 sec */ time_t firsttime; time(&firsttime); while (1) { CheckForTimeout(readsocket); PingAllPlayer(readsocket, firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); select(readsocket + 1, &descriptor, NULL, NULL, NULL); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown if (id != -1)///When the player is known execute other commands as when the player is unknown { if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; /** * This while construct splits the recieved UDP-message * into cs2d-messages. * Every packet function returns the count of read bytes. */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } /** * Security check (Buffer Overflow) */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return EXIT_SUCCESS; } diff --git a/src/respond_messages.c b/src/respond_messages.c index b1ff09e..82bdfe2 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,573 +1,574 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer+position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = strlen(player[id].name); position++; memcpy(buffer+position, player[id].name, strlen(player[id].name)); position += strlen(player[id].name); buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket, time_t firsttime) { time_t actualtime; time(&actualtime); if(actualtime >= (firsttime + 5)) { firsttime = actualtime; SendPingList(writesocket); + SendMessageToAll("This is an alpha version! Don't play at it!", 1, writesocket); //Do not remove or change this until server reaches beta status int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int writesocket) { /* int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = hitter; position++; buffer[position] = victim; position++; buffer[position] = wpnid; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); */ } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count*3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for(i = 1; i<= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer+position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); }
Jermuk/custom_cs2dsrv
b5091477b832deb726a6fd1180d1ae80271bef11
- More comments added (for documentatin and also for understanding)
diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe index bb8f899..6586c86 100644 Binary files a/Release/custom_cs2dsrv.exe and b/Release/custom_cs2dsrv.exe differ
Jermuk/custom_cs2dsrv
3b1cb59862ec8aefaf98c4f686adfba3c37513f0
- Added more comments (for documentation and also for understanding the code)
diff --git a/include/main.h b/include/main.h index 09d1aae..f4acaa2 100644 --- a/include/main.h +++ b/include/main.h @@ -1,42 +1,44 @@ #ifndef MAIN_H_INCLUDED #define MAIN_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdarg.h> //log.h #include <math.h> //aim #define PI 3.14159265 #ifdef _WIN32 #include <winsock.h> #include <io.h> #else #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/select.h> //for select() #endif /* Self-made includes */ #include "log.h" #include "settings.h" #include "structs.h" #include "weapons.h" #include "cross_layer.h" #include "functions.h" #include "sendto_functions.h" #include "respond_messages.h" #include "pakets.h" #include "script-functions.h" #include "map.h" +int main(); + #endif // MAIN_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index be74182..6d387d9 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,23 +1,23 @@ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket); void SendMessageToAll(unsigned char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); -void PingAllPlayer(int writesocket); +void PingAllPlayer(int writesocket, time_t firsttime); void SendReloadMessage(int id, int status, int writesocket); void SendPingList(int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/src/functions.c b/src/functions.c index 07dc304..ac026e4 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,418 +1,416 @@ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success - * \note still not working * - * TODO PlayerTimeout is still not working */ int PlayerTimeout(int id) { //id = 0; time_t actualtime; time(&actualtime); if(((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket != 0) { return 1; } return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if(strcmp(sv_password, "")) { serverstatus += 1; } if(sv_usgnonly == 1) { serverstatus += 2; } if(sv_fow == 1) { serverstatus += 4; } if(sv_friendlyfire == 1) { serverstatus += 8; } if(1) //Same Version? { serverstatus += 16; } if(sv_gamemode != 0) { serverstatus += 32; } if(0) //LuaScripts { serverstatus += 64; } if(1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x>>8) | (*x<<8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 != 0) { if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if(*pTempNummer-1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer+1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(char *password) { if(strcmp(sv_password, password) != 0) { printf("Password wrong!\n"); return 1; } if(sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length+1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** - * \fn void CheckAllPlayerForReload(void) - * \brief check all player if their reload is ended - * ,send message if necessary, and rise their magazine + * \fn void CheckAllPlayerForReload(int writesocket) + * \brief check all player if their reload is ended, + * send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].reloading != 0) { if(player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if(player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } diff --git a/src/log.c b/src/log.c index b4c3446..049ecbd 100644 --- a/src/log.c +++ b/src/log.c @@ -1,69 +1,81 @@ #include "../include/log.h" +/** + * \fn void myprintf(char *string, ...) + * \brief prints string with time to stdout and logfile + * \param *string the string to print out (same syntax as printf) + * \param ... the other parameters, if necessary + */ void myprintf(char *string, ...) { #ifdef _WIN32 FILE *logfile; time_t rawtime; struct tm * timeinfo; logfile = fopen("log.txt","a+"); if(logfile != NULL) { time(&rawtime); timeinfo = localtime(&rawtime); //fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); //vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } #else time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); va_end(argzeiger); #endif } +/** + * \fn void myprintf2(char *string, ...) + * \brief same as myprintf, just with the difference, that the time won't be printed + * \param *string the string to print out (same syntax as printf) + * \param ... the other parameters, if necessary + */ void myprintf2(char *string, ...) { #ifdef _WIN32 FILE *logfile; logfile = fopen("log.txt","a+"); if(logfile != NULL) { va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } #else va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); va_end(argzeiger); #endif } diff --git a/src/main.c b/src/main.c index ea19f0e..db78a12 100644 --- a/src/main.c +++ b/src/main.c @@ -1,219 +1,241 @@ #include "../include/main.h" -time_t firsttime; +/** + * \fn int main() + * \brief initialize sockets and if a message was recieved, give it to the right function. + * \return EXIT_SUCCESS or EXIT_FAILURE + */ int main() { + /** + * Initalize variables, weapons, players and sockets + */ int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); + + /** + * \var needed for PingAllPlayer() to execute it every 5 sec + */ + time_t firsttime; time(&firsttime); while (1) { - CheckForTimeout(readsocket); - PingAllPlayer(readsocket); + PingAllPlayer(readsocket, firsttime); /// also execute PingList() CheckAllPlayerForReload(readsocket); select(readsocket + 1, &descriptor, NULL, NULL, NULL); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { - int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); - if (id != -1) + int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); /// Function returns id or -1 if unknown + if (id != -1)///When the player is known execute other commands as when the player is unknown { - if (ValidatePaket(buffer, id)) + if (ValidatePaket(buffer, id)) ///Checks and raise the packet numbering if necessary { - PaketConfirmation(buffer, id, readsocket); + PaketConfirmation(buffer, id, readsocket); ///If the numbering is even, send a confirmation time(&player[id].lastpaket); int control = 1; int position = 2; + /** + * This while construct splits the recieved UDP-message + * into cs2d-messages. + * Every packet function returns the count of read bytes. + */ while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } + /** + * Security check (Buffer Overflow) + */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } + /** + * Security check (Buffer Overflow) + */ else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } - return 0; + return EXIT_SUCCESS; } diff --git a/src/map.c b/src/map.c index e1d64d0..77afadd 100644 --- a/src/map.c +++ b/src/map.c @@ -1,184 +1,206 @@ #include "../include/map.h" +/** + * \fn void ReadMap() + * \brief reads the map and put all needed information into a variable + * needed: tspawn and ctspawn + */ void ReadMap() { FILE *file; int i; tspawncount = 0; ctspawncount = 0; char *mappath = malloc(strlen(sv_map) + 5); memcpy(mappath, sv_map, strlen(sv_map)); memcpy(mappath + strlen(sv_map), ".map\0", 5); file = fopen(mappath, "rb"); if (file == NULL) error_exit("Map not found.. Abort\n"); else printf("Loading '%s'..", mappath); free(mappath); //------------------------------ unsigned char *mapheader = ReadLine(file); for (i = 1; i <= 9; i++) ReadByte(file); for (i = 1; i <= 10; i++) ReadInt(file); for (i = 1; i <= 10; i++) ReadLine(file); unsigned char *code = ReadLine(file); unsigned char *tileset = ReadLine(file); unsigned char loaded = ReadByte(file); int maxx = ReadInt(file); int maxy = ReadInt(file); unsigned char *background = ReadLine(file); int backgroundx = ReadInt(file); int backgroundy = ReadInt(file); unsigned char red = ReadByte(file); unsigned char green = ReadByte(file); unsigned char blue = ReadByte(file); unsigned char *mapcheck = ReadLine(file); //----------------------------------------- unsigned char *tilemode = malloc(loaded + 1); if (tilemode == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= loaded; i++) { tilemode[i] = ReadByte(file); } map = malloc(maxx * sizeof(struct TILE *)); if (map == NULL) error_exit("Memory error in ReadMap()\n"); for (i = 0; i <= maxx; i++) { map[i] = malloc(maxy * sizeof(struct TILE *)); if (map[i] == NULL) error_exit("Memory error in ReadMap()\n"); int b; for (b = 0; b <= maxy; b++) { unsigned char bytecache = ReadByte(file); if (bytecache > loaded) { bytecache = 0; } map[i][b].tileid = bytecache; map[i][b].mode = tilemode[bytecache]; //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); } } //--------------------------------------- unsigned char enities_count = ReadByte(file); for (i = 0; i <= enities_count - 1; i++) { unsigned char *name = ReadLine(file); unsigned char typ = ReadByte(file); int x = ReadInt(file); int y = ReadInt(file); unsigned char *trigger = ReadLine(file); //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); int b; for (b = 0; b <= 9; b++) { int unknownint = ReadInt(file); unsigned char *unknown = ReadLine(file); //eprintf("(%d) %s || ", unknownint, unknown); free(unknown); } switch (typ) { case 0: { tspawnx[tspawncount] = x; tspawny[tspawncount] = y; tspawncount++; break; } case 1: { ctspawnx[ctspawncount] = x; ctspawny[ctspawncount] = y; ctspawncount++; break; } default: { break; } } free(name); free(trigger); } fclose(file); eprintf("loaded!\n"); free(mapheader); free(code); free(tileset); free(background); free(mapcheck); } +/** + * \fn unsigned char *ReadLine(FILE *file) + * \brief read from a file stream a cs2d line (ends with \r\n; windows end) + * \param *file the file stream + * \return a pointer to the read line + */ unsigned char *ReadLine(FILE *file) { int position = 0; char *line = NULL; char c; while ((c = fgetc(file)) != 13) { if (c == EOF) error_exit("EndOfFile in ReadByte()\n"); line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = c; position++; } line = realloc(line, position + 1); if (line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = '\0'; position++; fgetc(file); //0x0A return line; } +/** + * \fn unsigned char ReadByte(FILE *file) + * \brief read from a file stream a byte + * \param *file the file stream + * \return the read byte + */ unsigned char ReadByte(FILE *file) { unsigned char byte = fgetc(file); if (byte == EOF) error_exit("EndOfFile in ReadByte()\n"); return byte; } - +/** + * \fn int ReadInt(FILE *file) + * \brief read from a file stream a integer + * \param *file the file stream + * \return the read integer + */ int ReadInt(FILE *file) { unsigned char byte1 = fgetc(file); if (byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte2 = fgetc(file); if (byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte3 = fgetc(file); if (byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte4 = fgetc(file); if (byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/pakets.c b/src/pakets.c index c6f9418..5cd2de0 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -1,888 +1,1037 @@ #include "../include/pakets.h" - +/** + * \fn int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) + * \brief every unknown packet lands here + * \param *message pointer to the unknown message + * \param length sizeof message + * \param *buffer pointer to the udp-packet + * \param size sizeof buffer + * \param position where the unknown message in buffer begins + * \return read bytes (specific: parameter length) + */ int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) { int paketlength = length; int i; printf("Unknown packet: "); for(i = 2; i <= position-1; i++) { eprintf("%d-", buffer[i]); } eprintf("\n\t"); for(i = 0; i <= length-1; i++) { eprintf("%d-", message[i]); } eprintf("\n"); return paketlength; } +/** + * \fn int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) + * \brief handles a connection setup for unknown player + * \param *message pointer to the unknown message + * \param length sizeof message + * \param ip clients ip + * \param port clients port + * \return read bytes (specific: 3) + */ int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_unknown)!\n"); return length; } return paketlength; } +/** + * \fn int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port) + * \brief handles a connection setup for known player + * \param *message pointer to the unknown message + * \param length sizeof message + * \param ip clients ip + * \param port clients port + * \return read bytes (specific: 3) + */ int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_known)!\n"); return length; } return paketlength; } +/** + * \fn int ping_ingame(unsigned char *message, int length, int id, int writesocket) + * \brief handles a answer from the server ingame ping. this function calculates the latency + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ int ping_ingame(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; - printf("%s: %d\n", player[id].name, player[id].latency); + //printf("%s: %d\n", player[id].name, player[id].latency); return paketlength; } +/** + * \fn int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) + * \brief handles a confirmation for unknown player + * \param *message pointer to the unknown message + * \param length sizeof message + * \param ip clients ip + * \param port clients port + * \return read bytes (specific: 3) + */ int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } +/** + * \fn int confirmation_known(unsigned char *message, int length, int id, int writesocket) + * \brief handles a confirmation for known player + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } +/** + * \fn int fire(unsigned char *message, int length, int id, int writesocket) + * \brief handles a fire + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 1) + */ int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch(OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } +/** + * \fn int buy(unsigned char *message, int length, int id, int writesocket) + * \brief handles a buy request + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnBuyAttempt(id, wpnid, writesocket)) { case 0: OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } +/** + * \fn int rotupdate(unsigned char *message, int length, int id, int writesocket) + * \brief handles a rotation update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if(length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message+1, sizeof(float)); if(temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } +/** + * \fn int posupdatewalk(unsigned char *message, int length, int id, int writesocket) + * \brief handles a position walk update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } - +/** + * \fn int posupdaterun(unsigned char *message, int length, int id, int writesocket) + * \brief handles a position run update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } - +/** + * \fn int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket)) + * \brief handles a position walk and rotation update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 9) + */ int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } +/** + * \fn int posrotupdaterun(unsigned char *message, int length, int id, int writesocket)) + * \brief handles a position run and rotation update + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 9) + */ int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } +/** + * \fn int respawnrequest(unsigned char *message, int length, int id, int writesocket) + * \brief handles a respawn request + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 1) + */ int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch(OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch(player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp]+0.5)*32; player[id].y = (tspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp]+0.5)*32; player[id].y = (ctspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } - +/** + * \fn int weaponchange(unsigned char *message, int length, int id, int writesocket) + * \brief handles a weapon change + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } +/** + * \fn int teamchange(unsigned char *message, int length, int id, int writesocket) + * \brief handles a team change + * \param *message pointer to the message + * \param length sizeof message + * \param id clients player id + * \param writesocket the socket where it was read + * \return read bytes (specific: 3) + */ int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch(OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if(skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } - +/** + * \fn int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) + * \brief handles a team change + * \param *message pointer to the message + * \param length sizeof message + * \param *client pointer to the client information structure + * \param writesocket the socket where it was read + * \return read bytes (specific: 5) + */ int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer+2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if(length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + strlen(sv_name) + strlen(sv_map); if(sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch(message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if(sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if(length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch(message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS-1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if(paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch(OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength=4; unsigned char team, unknown; int paketsize; if(paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length-position+1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(string, message+position, paketsize); string[paketsize] = '\0'; position += paketsize; switch(OnChatMessage(id, string, team, writesocket)) { case 0: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch(message[1]) { case 0: { paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if(player[id].joinstatus == 1) { paketlength = 16; // ??? if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; player[id].name = malloc(stringsize); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message+position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; unsigned char *password = malloc(stringsize); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message+position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; for (i = 0; i <= strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; unsigned char *encryption1 = malloc(stringsize); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message+position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message+position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes /* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif */ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; player[id].spraylogo = malloc(stringsize); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message+position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; unsigned char *maphash= malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message+position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; player[id].win= malloc(stringsize); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message+position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; //printf("\tWIN: %s (%d)\n", player[id].win, strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch(tempstatus) { case 0x00: stringsize = 6 + strlen(sv_map) + strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); position += strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } //stringsize = 16 + strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if(stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if(player[id].joinstatus == 2) { int position = 2; paketlength = 5; if(paketlength > length) diff --git a/src/respond_messages.c b/src/respond_messages.c index 477607f..b1ff09e 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,573 +1,573 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer+position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = strlen(player[id].name); position++; memcpy(buffer+position, player[id].name, strlen(player[id].name)); position += strlen(player[id].name); buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } -void PingAllPlayer(int writesocket) +void PingAllPlayer(int writesocket, time_t firsttime) { time_t actualtime; time(&actualtime); if(actualtime >= (firsttime + 5)) { firsttime = actualtime; - //SendPingList(writesocket); + SendPingList(writesocket); int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } //FIXME complete SendKillMessage void SendKillMessage(int id, int writesocket) { /* int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = hitter; position++; buffer[position] = victim; position++; buffer[position] = wpnid; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); */ } void SendPingList(int writesocket) { int count = onlineplayer; int stringsize = 2 + count*3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); int position = 0; buffer[position] = 247; position++; buffer[position] = count; position++; int i; for(i = 1; i<= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { buffer[position] = i; position++; memcpy(buffer+position, &player[i].latency, 2); position += 2; /* buffer[position] = player[i].latency; position++; buffer[position] = 0; position++; */ } } SendToAll(buffer, stringsize, 0, writesocket); free(buffer); }
Jermuk/custom_cs2dsrv
949de290a1604e2529cf01f8b9af87d8cd61bd83
- Player[id].latency to unsigned short
diff --git a/include/structs.h b/include/structs.h index 99ffec1..d2a6b78 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,75 +1,75 @@ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; float freq; short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; }; struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; }; struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; time_t lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; short deaths, score; unsigned short x,y; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; unsigned short kills; int reloadtimer, reloading; short dead; int start; - int latency; + unsigned short latency; int firetimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED
Jermuk/custom_cs2dsrv
81db3e5bc1cb5dcb8b428e02e47e49c0d56fac6e
- Removed redundant files and added .exe
diff --git a/.cproject b/.cproject deleted file mode 100644 index 4a8405e..0000000 --- a/.cproject +++ /dev/null @@ -1,628 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<?fileVersion 4.0.0?> - -<cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage"> - <storageModule moduleId="org.eclipse.cdt.core.settings"> - <cconfiguration id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458"> - <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458" moduleId="org.eclipse.cdt.core.settings" name="Debug"> - <externalSettings/> - <extensions> - <extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/> - <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> - <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> - <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> - </extensions> - </storageModule> - <storageModule moduleId="cdtBuildSystem" version="4.0.0"> - <configuration artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.exe" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.exe" cleanCommand="rm -rf" description="" id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458" name="Debug" parent="cdt.managedbuild.config.gnu.mingw.exe.debug"> - <folderInfo id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458." name="/" resourcePath=""> - <toolChain id="cdt.managedbuild.toolchain.gnu.mingw.exe.debug.1188392895" name="MinGW GCC" superClass="cdt.managedbuild.toolchain.gnu.mingw.exe.debug"> - <targetPlatform id="cdt.managedbuild.target.gnu.platform.mingw.exe.debug.433122987" name="Debug Platform" superClass="cdt.managedbuild.target.gnu.platform.mingw.exe.debug"/> - <builder buildPath="${workspace_loc:/custom_cs2dsrv/Debug}" id="cdt.managedbuild.tool.gnu.builder.mingw.base.442254957" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="CDT Internal Builder" superClass="cdt.managedbuild.tool.gnu.builder.mingw.base"/> - <tool id="cdt.managedbuild.tool.gnu.assembler.mingw.exe.debug.172730339" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.mingw.exe.debug"> - <inputType id="cdt.managedbuild.tool.gnu.assembler.input.671771288" superClass="cdt.managedbuild.tool.gnu.assembler.input"/> - </tool> - <tool id="cdt.managedbuild.tool.gnu.archiver.mingw.base.452536062" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.mingw.base"/> - <tool id="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.debug.1125479542" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.debug"> - <option id="gnu.cpp.compiler.mingw.exe.debug.option.optimization.level.856167253" name="Optimization Level" superClass="gnu.cpp.compiler.mingw.exe.debug.option.optimization.level" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/> - <option id="gnu.cpp.compiler.mingw.exe.debug.option.debugging.level.1286427477" name="Debug Level" superClass="gnu.cpp.compiler.mingw.exe.debug.option.debugging.level" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/> - </tool> - <tool id="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug"> - <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.mingw.exe.debug.option.optimization.level.899548284" name="Optimization Level" superClass="gnu.c.compiler.mingw.exe.debug.option.optimization.level" valueType="enumerated"/> - <option id="gnu.c.compiler.mingw.exe.debug.option.debugging.level.218260318" name="Debug Level" superClass="gnu.c.compiler.mingw.exe.debug.option.debugging.level" value="gnu.c.debugging.level.max" valueType="enumerated"/> - <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.293456763" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/> - </tool> - <tool id="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.debug.237306527" name="MinGW C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.debug"> - <option id="gnu.c.link.option.libs.696325141" name="Libraries (-l)" superClass="gnu.c.link.option.libs" valueType="libs"> - <listOptionValue builtIn="false" value="wsock32"/> - </option> - <option id="gnu.c.link.option.paths.1944619386" name="Library search path (-L)" superClass="gnu.c.link.option.paths" valueType="libPaths"> - <listOptionValue builtIn="false" value="&quot;C:\MinGW32\lib\&quot;"/> - </option> - <inputType id="cdt.managedbuild.tool.gnu.c.linker.input.1057549252" superClass="cdt.managedbuild.tool.gnu.c.linker.input"> - <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> - <additionalInput kind="additionalinput" paths="$(LIBS)"/> - </inputType> - </tool> - <tool id="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.debug.715096099" name="MinGW C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.debug"/> - </toolChain> - </folderInfo> - </configuration> - </storageModule> - <storageModule moduleId="scannerConfiguration"> - <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="makefileGenerator"> - <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827;cdt.managedbuild.config.gnu.mingw.exe.release.1594405827.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424;cdt.managedbuild.tool.gnu.c.compiler.input.191950135"> - <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="makefileGenerator"> - <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - </scannerConfigBuildInfo> - <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458;cdt.managedbuild.config.gnu.mingw.exe.debug.133679458.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703;cdt.managedbuild.tool.gnu.c.compiler.input.293456763"> - <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="makefileGenerator"> - <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - </scannerConfigBuildInfo> - </storageModule> - <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> - <storageModule moduleId="org.eclipse.cdt.make.core.buildtargets"> - <buildTargets> - <target name="cs2dsrv" path="src" targetID="org.eclipse.cdt.build.MakeTargetBuilder"> - <buildCommand>make</buildCommand> - <buildArguments/> - <buildTarget>cs2dsrv</buildTarget> - <stopOnError>true</stopOnError> - <useDefaultCommand>true</useDefaultCommand> - <runAllBuilders>true</runAllBuilders> - </target> - </buildTargets> - </storageModule> - </cconfiguration> - <cconfiguration id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827"> - <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827" moduleId="org.eclipse.cdt.core.settings" name="Release"> - <externalSettings/> - <extensions> - <extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/> - <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> - <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> - <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> - </extensions> - </storageModule> - <storageModule moduleId="cdtBuildSystem" version="4.0.0"> - <configuration artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.exe" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.exe" cleanCommand="rm -rf" description="" id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827" name="Release" parent="cdt.managedbuild.config.gnu.mingw.exe.release"> - <folderInfo id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827." name="/" resourcePath=""> - <toolChain id="cdt.managedbuild.toolchain.gnu.mingw.exe.release.1830096364" name="MinGW GCC" superClass="cdt.managedbuild.toolchain.gnu.mingw.exe.release"> - <targetPlatform id="cdt.managedbuild.target.gnu.platform.mingw.exe.release.199043754" name="Debug Platform" superClass="cdt.managedbuild.target.gnu.platform.mingw.exe.release"/> - <builder buildPath="${workspace_loc:/custom_cs2dsrv/Release}" id="cdt.managedbuild.tool.gnu.builder.mingw.base.781603840" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="CDT Internal Builder" superClass="cdt.managedbuild.tool.gnu.builder.mingw.base"/> - <tool id="cdt.managedbuild.tool.gnu.assembler.mingw.exe.release.1948519560" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.mingw.exe.release"> - <inputType id="cdt.managedbuild.tool.gnu.assembler.input.455298474" superClass="cdt.managedbuild.tool.gnu.assembler.input"/> - </tool> - <tool id="cdt.managedbuild.tool.gnu.archiver.mingw.base.884564668" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.mingw.base"/> - <tool id="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.release.629144444" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.release"> - <option id="gnu.cpp.compiler.mingw.exe.release.option.optimization.level.1969272803" name="Optimization Level" superClass="gnu.cpp.compiler.mingw.exe.release.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/> - <option id="gnu.cpp.compiler.mingw.exe.release.option.debugging.level.22968446" name="Debug Level" superClass="gnu.cpp.compiler.mingw.exe.release.option.debugging.level" value="gnu.cpp.compiler.debugging.level.none" valueType="enumerated"/> - </tool> - <tool id="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release"> - <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.mingw.exe.release.option.optimization.level.1005366988" name="Optimization Level" superClass="gnu.c.compiler.mingw.exe.release.option.optimization.level" valueType="enumerated"/> - <option id="gnu.c.compiler.mingw.exe.release.option.debugging.level.180917112" name="Debug Level" superClass="gnu.c.compiler.mingw.exe.release.option.debugging.level" value="gnu.c.debugging.level.none" valueType="enumerated"/> - <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.191950135" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/> - </tool> - <tool id="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.release.376579228" name="MinGW C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.release"> - <option id="gnu.c.link.option.libs.879542908" name="Libraries (-l)" superClass="gnu.c.link.option.libs" valueType="libs"> - <listOptionValue builtIn="false" value="wsock32"/> - </option> - <option id="gnu.c.link.option.paths.599340942" name="Library search path (-L)" superClass="gnu.c.link.option.paths" valueType="libPaths"> - <listOptionValue builtIn="false" value="&quot;C:\MinGW32\lib\&quot;"/> - </option> - <inputType id="cdt.managedbuild.tool.gnu.c.linker.input.465269045" superClass="cdt.managedbuild.tool.gnu.c.linker.input"> - <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> - <additionalInput kind="additionalinput" paths="$(LIBS)"/> - </inputType> - </tool> - <tool id="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.release.963626972" name="MinGW C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.release"/> - </toolChain> - </folderInfo> - </configuration> - </storageModule> - <storageModule moduleId="scannerConfiguration"> - <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="makefileGenerator"> - <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827;cdt.managedbuild.config.gnu.mingw.exe.release.1594405827.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424;cdt.managedbuild.tool.gnu.c.compiler.input.191950135"> - <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="makefileGenerator"> - <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - </scannerConfigBuildInfo> - <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458;cdt.managedbuild.config.gnu.mingw.exe.debug.133679458.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703;cdt.managedbuild.tool.gnu.c.compiler.input.293456763"> - <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="makefileGenerator"> - <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> - <buildOutputProvider> - <openAction enabled="true" filePath=""/> - <parser enabled="true"/> - </buildOutputProvider> - <scannerInfoProvider id="specsFile"> - <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> - <parser enabled="true"/> - </scannerInfoProvider> - </profile> - </scannerConfigBuildInfo> - </storageModule> - <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> - <storageModule moduleId="org.eclipse.cdt.make.core.buildtargets"> - <buildTargets> - <target name="cs2dsrv" path="src" targetID="org.eclipse.cdt.build.MakeTargetBuilder"> - <buildCommand>make</buildCommand> - <buildArguments/> - <buildTarget>cs2dsrv</buildTarget> - <stopOnError>true</stopOnError> - <useDefaultCommand>true</useDefaultCommand> - <runAllBuilders>true</runAllBuilders> - </target> - </buildTargets> - </storageModule> - </cconfiguration> - </storageModule> - <storageModule moduleId="cdtBuildSystem" version="4.0.0"> - <project id="custom_cs2dsrv.cdt.managedbuild.target.gnu.mingw.exe.750583817" name="Executable" projectType="cdt.managedbuild.target.gnu.mingw.exe"/> - </storageModule> -</cproject> diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..85f5ac0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +html +Debug +.settings +.cproject +.project +doxygen.Doxyfile +*.txt +Release/src +*.map diff --git a/.project b/.project deleted file mode 100644 index 2dad120..0000000 --- a/.project +++ /dev/null @@ -1,70 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>custom_cs2dsrv</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name> - <triggers>clean,full,incremental,</triggers> - <arguments> - <dictionary> - <key>?name?</key> - <value></value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.append_environment</key> - <value>true</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.buildArguments</key> - <value></value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.buildCommand</key> - <value>make</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.buildLocation</key> - <value>${workspace_loc:/custom_cs2dsrv/Release}</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.contents</key> - <value>org.eclipse.cdt.make.core.activeConfigSettings</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.enableAutoBuild</key> - <value>false</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.enableCleanBuild</key> - <value>true</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.enableFullBuild</key> - <value>true</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.stopOnError</key> - <value>true</value> - </dictionary> - <dictionary> - <key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key> - <value>true</value> - </dictionary> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name> - <triggers>full,incremental,</triggers> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.cdt.core.cnature</nature> - <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature> - <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature> - </natures> -</projectDescription> diff --git a/.settings/org.eclipse.cdt.managedbuilder.core.prefs b/.settings/org.eclipse.cdt.managedbuilder.core.prefs deleted file mode 100644 index 5cd5819..0000000 --- a/.settings/org.eclipse.cdt.managedbuilder.core.prefs +++ /dev/null @@ -1,22 +0,0 @@ -#Tue Oct 12 19:59:12 CEST 2010 -eclipse.preferences.version=1 -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/CPATH/delimiter=; -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/CPATH/operation=remove -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/C_INCLUDE_PATH/delimiter=; -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/C_INCLUDE_PATH/operation=remove -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/append=true -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/appendContributed=true -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/CPATH/delimiter=; -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/CPATH/operation=remove -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/C_INCLUDE_PATH/delimiter=; -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/C_INCLUDE_PATH/operation=remove -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/append=true -environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/appendContributed=true -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/LIBRARY_PATH/delimiter=; -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/LIBRARY_PATH/operation=remove -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/append=true -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/appendContributed=true -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/LIBRARY_PATH/delimiter=; -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/LIBRARY_PATH/operation=remove -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/append=true -environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/appendContributed=true diff --git a/.settings/org.eclipse.ltk.core.refactoring.prefs b/.settings/org.eclipse.ltk.core.refactoring.prefs deleted file mode 100644 index 4a2a7a3..0000000 --- a/.settings/org.eclipse.ltk.core.refactoring.prefs +++ /dev/null @@ -1,3 +0,0 @@ -#Wed Oct 13 12:44:35 CEST 2010 -eclipse.preferences.version=1 -org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false diff --git a/.settings/org.eclipse.mylyn.tasks.ui.prefs b/.settings/org.eclipse.mylyn.tasks.ui.prefs deleted file mode 100644 index 89dd593..0000000 --- a/.settings/org.eclipse.mylyn.tasks.ui.prefs +++ /dev/null @@ -1,4 +0,0 @@ -#Wed Oct 13 12:44:35 CEST 2010 -eclipse.preferences.version=1 -project.repository.kind=local -project.repository.url=local diff --git a/Release/custom_cs2dsrv.exe b/Release/custom_cs2dsrv.exe new file mode 100644 index 0000000..bb8f899 Binary files /dev/null and b/Release/custom_cs2dsrv.exe differ
Jermuk/custom_cs2dsrv
9ede4e46e362eb44aacff95e676f2b1f9db0f6ce
- Added Pinglist (not tested)
diff --git a/include/respond_messages.h b/include/respond_messages.h index 9f5247f..be74182 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,22 +1,23 @@ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket); void SendMessageToAll(unsigned char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); void PingAllPlayer(int writesocket); void SendReloadMessage(int id, int status, int writesocket); +void SendPingList(int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/src/main.c b/src/main.c index ace1a45..ea19f0e 100644 --- a/src/main.c +++ b/src/main.c @@ -1,220 +1,219 @@ #include "../include/main.h" time_t firsttime; int main() { int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); time(&firsttime); while (1) { CheckForTimeout(readsocket); PingAllPlayer(readsocket); CheckAllPlayerForReload(readsocket); select(readsocket + 1, &descriptor, NULL, NULL, NULL); if (FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); if (id != -1) { if (ValidatePaket(buffer, id)) { PaketConfirmation(buffer, id, readsocket); time(&player[id].lastpaket); int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: - rtn - = specpos(message, tempsize, id, + rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while (control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer + position, tempsize); int rtn = 0; switch (message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return 0; } diff --git a/src/pakets.c b/src/pakets.c index 79de8db..c6f9418 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -1,565 +1,566 @@ #include "../include/pakets.h" int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) { int paketlength = length; int i; printf("Unknown packet: "); for(i = 2; i <= position-1; i++) { eprintf("%d-", buffer[i]); } eprintf("\n\t"); for(i = 0; i <= length-1; i++) { eprintf("%d-", message[i]); } eprintf("\n"); return paketlength; } int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_unknown)!\n"); return length; } return paketlength; } int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_known)!\n"); return length; } return paketlength; } int ping_ingame(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; + printf("%s: %d\n", player[id].name, player[id].latency); return paketlength; } int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch(OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnBuyAttempt(id, wpnid, writesocket)) { case 0: OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if(length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message+1, sizeof(float)); if(temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch(OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch(player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp]+0.5)*32; player[id].y = (tspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp]+0.5)*32; player[id].y = (ctspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch(OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if(skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer+2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if(length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + strlen(sv_name) + strlen(sv_map); if(sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch(message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if(sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if(length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch(message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS-1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if(paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch(OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; diff --git a/src/respond_messages.c b/src/respond_messages.c index d4b936a..477607f 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,512 +1,573 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer+position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = strlen(player[id].name); position++; memcpy(buffer+position, player[id].name, strlen(player[id].name)); position += strlen(player[id].name); buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket) { time_t actualtime; time(&actualtime); if(actualtime >= (firsttime + 5)) { firsttime = actualtime; + //SendPingList(writesocket); int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } void SendReloadMessage(int id, int status, int writesocket) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); - if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); + if (buffer == NULL) error_exit("Memory error ( SendReloadMessage() )\n"); int position = 0; buffer[position] = 16; position++; buffer[position] = id; position++; buffer[position] = status; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } +//FIXME complete SendKillMessage +void SendKillMessage(int id, int writesocket) +{ + + /* + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendKillMessage() )\n"); + + int position = 0; + + buffer[position] = 16; + position++; + buffer[position] = hitter; + position++; + buffer[position] = victim; + position++; + buffer[position] = wpnid; + position++; + + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); + */ +} + +void SendPingList(int writesocket) +{ + int count = onlineplayer; + int stringsize = 2 + count*3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendPingList() )\n"); + + int position = 0; + + buffer[position] = 247; + position++; + buffer[position] = count; + position++; + int i; + for(i = 1; i<= sv_maxplayers; i++) + { + if(player[i].used == 1 && player[i].joinstatus >= 4) + { + buffer[position] = i; + position++; + memcpy(buffer+position, &player[i].latency, 2); + position += 2; + /* + buffer[position] = player[i].latency; + position++; + buffer[position] = 0; + position++; + */ + } + } + + SendToAll(buffer, stringsize, 0, writesocket); + free(buffer); +}
Jermuk/custom_cs2dsrv
7fe3cc191a022794885ec8f86701f86c05f65032
- Fixed teamchange (player die now)
diff --git a/src/main.c b/src/main.c index c68bcb3..ace1a45 100644 --- a/src/main.c +++ b/src/main.c @@ -1,195 +1,220 @@ #include "../include/main.h" time_t firsttime; int main() { - int readsocket; - struct sockaddr_in newclient; - unsigned char buffer[MAX_BUF]; - int size; - fd_set descriptor; //I don't know - - ClearAllPlayer(); - WeaponInit(); - - readsocket = create_socket(); - bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); - atexit(cleanup); - - FD_ZERO(&descriptor); - FD_SET(readsocket, &descriptor); - - OnServerStart(); - ReadMap(); - time(&firsttime); - while(1) - { - - CheckForTimeout(readsocket); - PingAllPlayer(readsocket); - CheckAllPlayerForReload(readsocket); - - select(readsocket+1, &descriptor, NULL, NULL, NULL); - - if(FD_ISSET(readsocket, &descriptor)) - { - size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); - //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); - - if (size < 3) - { - printf("Invalid paket! (size < 3)\n"); - } - else - { - int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); - if(id != -1) - { - if (ValidatePaket(buffer, id)) - { - PaketConfirmation(buffer, id, readsocket); - time(&player[id].lastpaket); - int control = 1; - int position = 2; - while(control) - { - int tempsize = size - position; - - unsigned char *message = malloc(tempsize); - memcpy(message, buffer+position, tempsize); - int rtn = 0; - - switch(message[0]) //payload - { - case 1: - rtn = confirmation_known(message, tempsize, id, readsocket); - break; - case 3: - rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); - break; - case 7: - rtn = fire(message, tempsize, id, readsocket); - break; - case 9: - rtn = weaponchange(message, tempsize, id, readsocket); - break; - case 10: - rtn = posupdaterun(message, tempsize, id, readsocket); - break; - case 11: - rtn = posupdatewalk(message, tempsize, id, readsocket); - break; - case 12: - rtn = rotupdate(message, tempsize, id, readsocket); - break; - case 13: - rtn = posrotupdaterun(message, tempsize, id, readsocket); - break; - case 14: - rtn = posrotupdatewalk(message, tempsize, id, readsocket); - break; - case 16: - rtn = reload(message, tempsize, id, readsocket); - break; - case 20: - rtn = teamchange(message, tempsize, id, readsocket); - break; - case 23: - rtn = buy(message, tempsize, id, readsocket); - break; - case 32: - rtn = specpos(message, tempsize, id, readsocket); - break; - case 39: - rtn = respawnrequest(message, tempsize, id, readsocket); - break; - case 240: - rtn = chatmessage(message, tempsize, id, readsocket); - break; - case 249: - rtn = ping_ingame(message, tempsize, id, readsocket); - break; - case 252: - rtn = joinroutine_known(message, tempsize, id, readsocket); - break; - case 253: - rtn = leave(id, readsocket); - break; - default: - SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); - unknown(message, tempsize, buffer, size, position); - rtn = tempsize; - break; - } - - position = position + rtn; - if (position == size) - { - free(message); - break; - } - else if (position > size) - { - printf("Error while reading packet: position(%d) > size(%d)\n", position, size); - free(message); - } - free(message); - } - } - } - else - { - int control = 1; - int position = 2; - while(control) - { - int tempsize = size - position; - - unsigned char *message = malloc(tempsize); - memcpy(message, buffer+position, tempsize); - int rtn = 0; - - switch(message[0]) //payload - { - case 1: - rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); - break; - case 3: - rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); - break; - case 250: - rtn = ping_serverlist(message, tempsize, &newclient, readsocket); - break; - case 251: - rtn = serverinfo_request(message, tempsize, &newclient, readsocket); - break; - case 252: - rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); - break; - default: - unknown(message, tempsize, buffer, size, position); - rtn = tempsize; - break; - } - - position = position + rtn; - if (position == size) - { - free(message); - break; - } - else if (position > size) - { - printf("Error while reading packet: position(%d) > size(%d)\n", position, size); - free(message); - } - free(message); - } - } - } - - } - } - return 0; + int readsocket; + struct sockaddr_in newclient; + unsigned char buffer[MAX_BUF]; + int size; + fd_set descriptor; //I don't know + + ClearAllPlayer(); + WeaponInit(); + + readsocket = create_socket(); + bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); + atexit(cleanup); + + FD_ZERO(&descriptor); + FD_SET(readsocket, &descriptor); + + OnServerStart(); + ReadMap(); + time(&firsttime); + while (1) + { + + CheckForTimeout(readsocket); + PingAllPlayer(readsocket); + CheckAllPlayerForReload(readsocket); + + select(readsocket + 1, &descriptor, NULL, NULL, NULL); + + if (FD_ISSET(readsocket, &descriptor)) + { + size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); + //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); + + if (size < 3) + { + printf("Invalid paket! (size < 3)\n"); + } + else + { + int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); + if (id != -1) + { + if (ValidatePaket(buffer, id)) + { + PaketConfirmation(buffer, id, readsocket); + time(&player[id].lastpaket); + int control = 1; + int position = 2; + while (control) + { + int tempsize = size - position; + + unsigned char *message = malloc(tempsize); + memcpy(message, buffer + position, tempsize); + int rtn = 0; + + switch (message[0]) + //payload + { + case 1: + rtn = confirmation_known(message, tempsize, id, + readsocket); + break; + case 3: + rtn = connection_setup_known(message, tempsize, + newclient.sin_addr, newclient.sin_port, + id); + break; + case 7: + rtn = fire(message, tempsize, id, readsocket); + break; + case 9: + rtn = weaponchange(message, tempsize, id, + readsocket); + break; + case 10: + rtn = posupdaterun(message, tempsize, id, + readsocket); + break; + case 11: + rtn = posupdatewalk(message, tempsize, id, + readsocket); + break; + case 12: + rtn = rotupdate(message, tempsize, id, + readsocket); + break; + case 13: + rtn = posrotupdaterun(message, tempsize, id, + readsocket); + break; + case 14: + rtn = posrotupdatewalk(message, tempsize, id, + readsocket); + break; + case 16: + rtn = reload(message, tempsize, id, readsocket); + break; + case 20: + rtn = teamchange(message, tempsize, id, + readsocket); + break; + case 23: + rtn = buy(message, tempsize, id, readsocket); + break; + case 32: + rtn + = specpos(message, tempsize, id, + readsocket); + break; + case 39: + rtn = respawnrequest(message, tempsize, id, + readsocket); + break; + case 240: + rtn = chatmessage(message, tempsize, id, + readsocket); + break; + case 249: + rtn = ping_ingame(message, tempsize, id, + readsocket); + break; + case 252: + rtn = joinroutine_known(message, tempsize, id, + readsocket); + break; + case 253: + rtn = leave(id, readsocket); + break; + default: + SendMessageToPlayer(id, "Not implemented yet!", + 1, readsocket); + unknown(message, tempsize, buffer, size, + position); + rtn = tempsize; + break; + } + + position = position + rtn; + if (position == size) + { + free(message); + break; + } + else if (position > size) + { + printf("Error while reading packet: position(%d) > size(%d)\n", position, size); + free(message); + } + free(message); + } + } + } + else + { + int control = 1; + int position = 2; + while (control) + { + int tempsize = size - position; + + unsigned char *message = malloc(tempsize); + memcpy(message, buffer + position, tempsize); + int rtn = 0; + + switch (message[0]) + //payload + { + case 1: + rtn = confirmation_unknown(message, tempsize, + newclient.sin_addr, newclient.sin_port); + break; + case 3: + rtn = connection_setup_unknown(message, tempsize, + newclient.sin_addr, newclient.sin_port); + break; + case 250: + rtn = ping_serverlist(message, tempsize, + &newclient, readsocket); + break; + case 251: + rtn = serverinfo_request(message, tempsize, + &newclient, readsocket); + break; + case 252: + rtn = joinroutine_unknown(message, tempsize, + &newclient, readsocket); + break; + default: + unknown(message, tempsize, buffer, size, position); + rtn = tempsize; + break; + } + + position = position + rtn; + if (position == size) + { + free(message); + break; + } + else if (position > size) + { + printf("Error while reading packet: position(%d) > size(%d)\n", position, size); + free(message); + } + free(message); + } + } + } + + } + } + return 0; } diff --git a/src/map.c b/src/map.c index 241d9ce..e1d64d0 100644 --- a/src/map.c +++ b/src/map.c @@ -1,171 +1,184 @@ #include "../include/map.h" void ReadMap() { - FILE *file; - int i; - tspawncount = 0; - ctspawncount = 0; - - char *mappath = malloc(strlen(sv_map)+5); - memcpy(mappath, sv_map, strlen(sv_map)); - memcpy(mappath+strlen(sv_map), ".map\0", 5); - - file = fopen(mappath,"rb"); - if(file == NULL) error_exit("Map not found.. Abort\n"); - else printf("Loading '%s'..", mappath); - - free(mappath); - - //------------------------------ - unsigned char *mapheader = ReadLine(file); - for(i = 1; i <= 9; i++) ReadByte(file); - for(i = 1; i <= 10; i++) ReadInt(file); - for(i = 1; i <= 10; i++) ReadLine(file); - unsigned char *code = ReadLine(file); - unsigned char *tileset = ReadLine(file); - unsigned char loaded = ReadByte(file); - int maxx = ReadInt(file); - int maxy = ReadInt(file); - unsigned char *background = ReadLine(file); - int backgroundx = ReadInt(file); - int backgroundy = ReadInt(file); - unsigned char red = ReadByte(file); - unsigned char green = ReadByte(file); - unsigned char blue = ReadByte(file); - unsigned char *mapcheck = ReadLine(file); - //----------------------------------------- - unsigned char *tilemode = malloc(loaded+1); - if(tilemode == NULL) error_exit("Memory error in ReadMap()\n"); - for(i = 0; i <= loaded; i++) - { - tilemode[i] = ReadByte(file); - } - - map = malloc(maxx * sizeof(struct TILE *)); - if(map == NULL) error_exit("Memory error in ReadMap()\n"); - for(i = 0; i <= maxx; i++) - { - map[i] = malloc(maxy * sizeof(struct TILE *)); - if(map[i] == NULL) error_exit("Memory error in ReadMap()\n"); - int b; - for(b = 0; b <= maxy; b++) - { - unsigned char bytecache = ReadByte(file); - if (bytecache > loaded) - { - bytecache = 0; - } - map[i][b].tileid = bytecache; - map[i][b].mode = tilemode[bytecache]; - //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); - } - } - //--------------------------------------- - unsigned char enities_count = ReadByte(file); - for(i = 0; i <= enities_count-1; i++) - { - unsigned char *name = ReadLine(file); - unsigned char typ = ReadByte(file); - int x = ReadInt(file); - int y = ReadInt(file); - unsigned char *trigger = ReadLine(file); - - //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); - int b; - for(b = 0; b <= 9; b++) - { - int unknownint = ReadInt(file); - unsigned char *unknown = ReadLine(file); - //eprintf("(%d) %s || ", unknownint, unknown); - free(unknown); - } - - - switch(typ) - { - case 0: - { - tspawnx[tspawncount] = x; - tspawny[tspawncount] = y; - tspawncount++; - break; - } - case 1: - { - ctspawnx[ctspawncount] = x; - ctspawny[ctspawncount] = y; - ctspawncount++; - break; - } - default: - { - break; - } - } - free(name); - free(trigger); - } - - fclose(file); - - eprintf("loaded!\n"); - free(mapheader); - free(code); - free(tileset); - free(background); - free(mapcheck); + FILE *file; + int i; + tspawncount = 0; + ctspawncount = 0; + + char *mappath = malloc(strlen(sv_map) + 5); + memcpy(mappath, sv_map, strlen(sv_map)); + memcpy(mappath + strlen(sv_map), ".map\0", 5); + + file = fopen(mappath, "rb"); + if (file == NULL) + error_exit("Map not found.. Abort\n"); + else printf("Loading '%s'..", mappath); + + free(mappath); + + //------------------------------ + unsigned char *mapheader = ReadLine(file); + for (i = 1; i <= 9; i++) + ReadByte(file); + for (i = 1; i <= 10; i++) + ReadInt(file); + for (i = 1; i <= 10; i++) + ReadLine(file); + unsigned char *code = ReadLine(file); + unsigned char *tileset = ReadLine(file); + unsigned char loaded = ReadByte(file); + int maxx = ReadInt(file); + int maxy = ReadInt(file); + unsigned char *background = ReadLine(file); + int backgroundx = ReadInt(file); + int backgroundy = ReadInt(file); + unsigned char red = ReadByte(file); + unsigned char green = ReadByte(file); + unsigned char blue = ReadByte(file); + unsigned char *mapcheck = ReadLine(file); + //----------------------------------------- + unsigned char *tilemode = malloc(loaded + 1); + if (tilemode == NULL) + error_exit("Memory error in ReadMap()\n"); + for (i = 0; i <= loaded; i++) + { + tilemode[i] = ReadByte(file); + } + + map = malloc(maxx * sizeof(struct TILE *)); + if (map == NULL) + error_exit("Memory error in ReadMap()\n"); + for (i = 0; i <= maxx; i++) + { + map[i] = malloc(maxy * sizeof(struct TILE *)); + if (map[i] == NULL) + error_exit("Memory error in ReadMap()\n"); + int b; + for (b = 0; b <= maxy; b++) + { + unsigned char bytecache = ReadByte(file); + if (bytecache > loaded) + { + bytecache = 0; + } + map[i][b].tileid = bytecache; + map[i][b].mode = tilemode[bytecache]; + //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); + } + } + //--------------------------------------- + unsigned char enities_count = ReadByte(file); + for (i = 0; i <= enities_count - 1; i++) + { + unsigned char *name = ReadLine(file); + unsigned char typ = ReadByte(file); + int x = ReadInt(file); + int y = ReadInt(file); + unsigned char *trigger = ReadLine(file); + + //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); + int b; + for (b = 0; b <= 9; b++) + { + int unknownint = ReadInt(file); + unsigned char *unknown = ReadLine(file); + //eprintf("(%d) %s || ", unknownint, unknown); + free(unknown); + } + + switch (typ) + { + case 0: + { + tspawnx[tspawncount] = x; + tspawny[tspawncount] = y; + tspawncount++; + break; + } + case 1: + { + ctspawnx[ctspawncount] = x; + ctspawny[ctspawncount] = y; + ctspawncount++; + break; + } + default: + { + break; + } + } + free(name); + free(trigger); + } + + fclose(file); + + eprintf("loaded!\n"); + free(mapheader); + free(code); + free(tileset); + free(background); + free(mapcheck); } - unsigned char *ReadLine(FILE *file) { - int position = 0; - char *line = NULL; - char c; - while( (c=fgetc(file)) != 13) - { - if(c == EOF) error_exit("EndOfFile in ReadByte()\n"); + int position = 0; + char *line = NULL; + char c; + while ((c = fgetc(file)) != 13) + { + if (c == EOF) + error_exit("EndOfFile in ReadByte()\n"); - line = realloc(line, position+1); - if(line == NULL) error_exit("Memory error in ReadLine()\n"); + line = realloc(line, position + 1); + if (line == NULL) + error_exit("Memory error in ReadLine()\n"); - line[position] = c; + line[position] = c; - position++; - } + position++; + } - line = realloc(line, position+1); - if(line == NULL) error_exit("Memory error in ReadLine()\n"); - line[position] = '\0'; - position++; + line = realloc(line, position + 1); + if (line == NULL) + error_exit("Memory error in ReadLine()\n"); + line[position] = '\0'; + position++; - fgetc(file); //0x0A + fgetc(file); //0x0A - return line; + return line; } unsigned char ReadByte(FILE *file) { - unsigned char byte = fgetc(file); - if(byte == EOF) error_exit("EndOfFile in ReadByte()\n"); - return byte; + unsigned char byte = fgetc(file); + if (byte == EOF) + error_exit("EndOfFile in ReadByte()\n"); + return byte; } int ReadInt(FILE *file) { - unsigned char byte1 = fgetc(file); - if(byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); + unsigned char byte1 = fgetc(file); + if (byte1 == EOF) + error_exit("EndOfFile in ReadInt()\n"); - unsigned char byte2 = fgetc(file); - if(byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); + unsigned char byte2 = fgetc(file); + if (byte2 == EOF) + error_exit("EndOfFile in ReadInt()\n"); - unsigned char byte3 = fgetc(file); - if(byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); + unsigned char byte3 = fgetc(file); + if (byte3 == EOF) + error_exit("EndOfFile in ReadInt()\n"); - unsigned char byte4 = fgetc(file); - if(byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); + unsigned char byte4 = fgetc(file); + if (byte4 == EOF) + error_exit("EndOfFile in ReadInt()\n"); - return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; + return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/script-functions.c b/src/script-functions.c index 86a0e12..5bab55b 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,385 +1,403 @@ #include "../include/script-functions.h" /* -int OnJoin(int id, int writesocket) -id - Who joins -Return Values: -0 - OK -*/ + int OnJoin(int id, int writesocket) + id - Who joins + Return Values: + 0 - OK + */ int OnJoin(int id, int writesocket) { - SendJoinMessage(id, writesocket); - printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); - return 0; + SendJoinMessage(id, writesocket); + printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); + return 0; } /* -int OnLeave(int id, int writesocket) -id - Who leaves -Return Values: -0 - OK -*/ + int OnLeave(int id, int writesocket) + id - Who leaves + Return Values: + 0 - OK + */ int OnLeave(int id, int writesocket) { - SendLeaveMessage(id, writesocket); - printf("%s has left the game!\n", player[id].name); - return 0; + SendLeaveMessage(id, writesocket); + printf("%s has left the game!\n", player[id].name); + return 0; } /* -int OnSpecmove(int id, int newx, int newy, int writesocket) -Return Values: -0 - OK -1 - Don't save it -*/ + int OnSpecmove(int id, int newx, int newy, int writesocket) + Return Values: + 0 - OK + 1 - Don't save it + */ int OnSpecmove(int id, int newx, int newy, int writesocket) { - return 0; + return 0; } /* -int OnServerstart() -Return Values: -0 - OK -*/ + int OnServerstart() + Return Values: + 0 - OK + */ int OnServerStart() { - time_t rawtime; - time(&rawtime); - printf("********** Server started **********\n"); - printf("%s", ctime(&rawtime)); - return 0; + time_t rawtime; + time(&rawtime); + printf("********** Server started **********\n"); + printf("%s", ctime(&rawtime)); + return 0; } /* -int OnExit() -Return Values: -0 - OK -*/ + int OnExit() + Return Values: + 0 - OK + */ int OnExit() { - printf("********** Server Shutdown! **********\n\n\n\n\n"); - return 0; + printf("********** Server Shutdown! **********\n\n\n\n\n"); + return 0; } /* -int OnRespawnRequest(int id, int writesocket) -Return Values: -0 - Respawn -1 - Don't Respawn -*/ + int OnRespawnRequest(int id, int writesocket) + Return Values: + 0 - Respawn + 1 - Don't Respawn + */ int OnRespawnRequest(int id, int writesocket) { - if(player[id].dead == 1) return 0; - else return 1; + if (player[id].dead == 1) + return 0; + else + return 1; } /* -int OnRespawn(int id, int writesocket) -Return Values: -0 - OK -*/ + int OnRespawn(int id, int writesocket) + Return Values: + 0 - OK + */ int OnRespawn(int id, int writesocket) { - return 0; + return 0; } /* -int OnRespawn(int id, int writesocket) -Return Values: -0 - OK -*/ + int OnRespawn(int id, int writesocket) + Return Values: + 0 - OK + */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { - int i; - for(i = 0; i <= 9; i++) - { - if(player[id].slot[i].id == wpnid) - { - player[id].actualweapon = i; - player[id].zoommode = 0; //CHANGE there are also silencer, ... - player[id].reloading = 0; + int i; + for (i = 0; i <= 9; i++) + { + if (player[id].slot[i].id == wpnid) + { + player[id].actualweapon = i; + player[id].zoommode = 0; //CHANGE there are also silencer, ... + player[id].reloading = 0; - printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); - return 0; - } - } - return 1; + printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); + return 0; + } + } + return 1; } /* -int OnFire(int id, int writesocket) -Return Values: -0 - OK -*/ + int OnFire(int id, int writesocket) + Return Values: + 0 - OK + */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); - short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; - if(*ammo1 <= 0 && *ammo1 != -1) - { - printf("Not enough ammo!\n"); - return 1; - } - else - { - if(*ammo1 != -1) - { - *ammo1 = *ammo1-1; - } - } - // TODO Firetimer does not work -/* - int temptime = mtime(); - printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); - if(temptime < player[id].firetimer) - { - printf("Firetimer error!"); - return 1; - } - else - { - player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; - //printf("(Debug) %d\n", player[id].firetimer); - } -*/ - int i; - int range = weapons[player[id].slot[player[id].actualweapon].id].range; + short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; + if (*ammo1 <= 0 && *ammo1 != -1) + { + printf("Not enough ammo!\n"); + return 1; + } + else + { + if (*ammo1 != -1) + { + *ammo1 = *ammo1 - 1; + } + } + // TODO Firetimer does not work + /* + int temptime = mtime(); + printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); + if(temptime < player[id].firetimer) + { + printf("Firetimer error!"); + return 1; + } + else + { + player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; + //printf("(Debug) %d\n", player[id].firetimer); + } + */ + int i; + int range = weapons[player[id].slot[player[id].actualweapon].id].range; - int startx = player[id].x; - int starty = player[id].y; - float rotx; - float roty; - float temprot = player[id].rotation; + int startx = player[id].x; + int starty = player[id].y; + float rotx; + float roty; + float temprot = player[id].rotation; - short playershit[MAX_CLIENTS] = {0}; + short playershit[MAX_CLIENTS] = + { 0 }; - if(temprot < 0) - { - temprot = 360 - (temprot *-1); - } - temprot = 360 - temprot; + if (temprot < 0) + { + temprot = 360 - (temprot * -1); + } + temprot = 360 - temprot; - temprot += 90; - if(temprot > 360) - { - temprot = temprot-360; - } + temprot += 90; + if (temprot > 360) + { + temprot = temprot - 360; + } - rotx = cos((temprot)*PI/180); - roty = sin((temprot)*PI/180); + rotx = cos((temprot) * PI / 180); + roty = sin((temprot) * PI / 180); - for(i = 1; i <= range; i++) - { - startx += i*rotx; - starty -= i*roty; + for (i = 1; i <= range; i++) + { + startx += i * rotx; + starty -= i * roty; - int tilex = (int)(startx)/32; - int tiley = (int)(starty)/32; + int tilex = (int) (startx) / 32; + int tiley = (int) (starty) / 32; - if(tilex <= 0 || tiley <= 0) break; - int tilemode = map[tilex][tiley].mode; - if(tilemode == 1 || tilemode == 3 || tilemode == 4) - { - break; - } + if (tilex <= 0 || tiley <= 0) + break; + int tilemode = map[tilex][tiley].mode; + if (tilemode == 1 || tilemode == 3 || tilemode == 4) + { + break; + } - int b; - for(b = 1; b <= sv_maxplayers; b++) - { - if(player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) - { - if(sqrt( (player[b].x - startx)*(player[b].x - startx) + (player[b].y - starty)*(player[b].y - starty) ) <= 16) - { - OnHit(id, b, writesocket); - playershit[b] = 1; - } - } - } - } - return 0; + int b; + for (b = 1; b <= sv_maxplayers; b++) + { + if (player[b].used == 1 && player[b].joinstatus >= 4 && b != id + && player[b].dead == 0 && playershit[b] == 0 + && player[id].team != player[b].team) + { + if (sqrt((player[b].x - startx) * (player[b].x - startx) + + (player[b].y - starty) * (player[b].y - starty)) + <= 16) + { + OnHit(id, b, writesocket); + playershit[b] = 1; + } + } + } + } + return 0; } /* -int OnHit(int hitter, int victim, int writesocket) -Return Values: -0 - OK -*/ + int OnHit(int hitter, int victim, int writesocket) + Return Values: + 0 - OK + */ int OnHit(int hitter, int victim, int writesocket) { - int wpnid = player[hitter].slot[player[hitter].actualweapon].id; - int damage; - switch(player[hitter].zoommode) - { - case 0: - damage = weapons[wpnid].weapondamage; - break; - case 1: - damage = weapons[wpnid].weapondamage_z1; - break; - case 2: - damage = weapons[wpnid].weapondamage_z2; - break; - default: - damage = weapons[wpnid].weapondamage; - break; - } - if(player[victim].health - damage > 0) - { - player[victim].health -= damage; - SendHitMessage(victim, hitter, player[victim].health, writesocket); - printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); - } - else - { - OnKill(hitter, victim, wpnid, writesocket); - } + int wpnid = player[hitter].slot[player[hitter].actualweapon].id; + int damage; + switch (player[hitter].zoommode) + { + case 0: + damage = weapons[wpnid].weapondamage; + break; + case 1: + damage = weapons[wpnid].weapondamage_z1; + break; + case 2: + damage = weapons[wpnid].weapondamage_z2; + break; + default: + damage = weapons[wpnid].weapondamage; + break; + } + if (player[victim].health - damage > 0) + { + player[victim].health -= damage; + SendHitMessage(victim, hitter, player[victim].health, writesocket); + printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); + } + else + { + OnKill(hitter, victim, wpnid, writesocket); + } - return 0; + return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { - if(player[id].money - weapons[wpnid].price >= 0) - { - int i; - for(i = 0; i <= 99; i++) - { - if(weapons[wpnid].freq != 0) //If weapon unknown -> everything is 0 - { - //Check if in buyzone - if(player[id].team == 1) - { - int b; - for(b = 0; b <= tspawncount; b++) - { - int playerx = player[id].x; - int playery = player[id].y; - int tempx = tspawnx[b]*32; - int tempy = tspawny[b]*32; - //If player in buyzone (5*5) - if(playerx >= tempx-64 && playerx <= tempx+64 && playery >= tempy-64 && playery <= tempy+64) - { - return 0; - } - } - } - else if(player[id].team == 2) - { - int b; - for(b = 0; b <= ctspawncount; b++) - { + if (player[id].money - weapons[wpnid].price >= 0) + { + int i; + for (i = 0; i <= 99; i++) + { + if (weapons[wpnid].freq != 0) //If weapon unknown -> everything is 0 + { + //Check if in buyzone + if (player[id].team == 1) + { + int b; + for (b = 0; b <= tspawncount; b++) + { + int playerx = player[id].x; + int playery = player[id].y; + int tempx = tspawnx[b] * 32; + int tempy = tspawny[b] * 32; + //If player in buyzone (5*5) + if (playerx >= tempx - 64 && playerx <= tempx + 64 + && playery >= tempy - 64 && playery <= tempy + + 64) + { + return 0; + } + } + } + else if (player[id].team == 2) + { + int b; + for (b = 0; b <= ctspawncount; b++) + { int playerx = player[id].x; int playery = player[id].y; - int tempx = ctspawnx[b]*32; - int tempy = ctspawny[b]*32; + int tempx = ctspawnx[b] * 32; + int tempy = ctspawny[b] * 32; //If player in buyzone (5*5) - if(playerx >= tempx-64 && playerx <= tempx+64 && playery >= tempy-64 && playery <= tempy+64) + if (playerx >= tempx - 64 && playerx <= tempx + 64 + && playery >= tempy - 64 && playery <= tempy + + 64) { return 0; } - } - } - } - } - } - return 1; + } + } + } + } + } + return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); - return 0; + return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { - player[victim].health = 0; - player[victim].dead = 1; - player[hitter].score++; - player[hitter].kills++; - player[victim].deaths++; - RemoveAllPlayerWeapon(victim); - SendHitMessage(victim, hitter, player[victim].health, writesocket); - printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); - return 0; + player[victim].health = 0; + player[victim].dead = 1; + player[hitter].score++; + player[hitter].kills++; + player[victim].deaths++; + RemoveAllPlayerWeapon(victim); + SendHitMessage(victim, hitter, player[victim].health, writesocket); + printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); + return 0; } /* -int OnChatMessage(int id, unsigned char *message, int team, int writesocket) -Return Values: -0 - OK -*/ + int OnChatMessage(int id, unsigned char *message, int team, int writesocket) + Return Values: + 0 - OK + */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { - if(team == 1) - { - printf("%s: %s\n", player[id].name, message); - } - else if(team == 2) - { - printf("%s (Team): %s\n", player[id].name, message); - } - SendChatMessage(id, message, team, writesocket); - return 0; + if (team == 1) + { + printf("%s: %s\n", player[id].name, message); + } + else if (team == 2) + { + printf("%s (Team): %s\n", player[id].name, message); + } + SendChatMessage(id, message, team, writesocket); + return 0; } /* -int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) -Return Values: -0 - OK -1 - Don't join -*/ -int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) + int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) + Return Values: + 0 - OK + 1 - Don't join + */ +int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, + int writesocket) { - return 0; + return 0; } /* -int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) -Return Values: -0 - OK -*/ -int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) + int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) + Return Values: + 0 - OK + */ +int OnTeamChange(int id, unsigned char team, unsigned char skin, + int writesocket) { - if(skin != 5) - { - switch(team) - { - case 0: - printf("%s is now spectator\n", player[id].name); - break; - case 1: - printf("%s is now terrorist\n", player[id].name); - break; - case 2: - printf("%s is now counter-terrorist\n", player[id].name); - break; - default: - printf("%s joined a unknown team\n", player[id].name); - break; - } - } - if(team <= 2) - { - SendTeamChangeMessage(id, team, skin, writesocket); - } - return 0; + if (skin != 5) + { + switch (team) + { + case 0: + printf("%s is now spectator\n", player[id].name); + break; + case 1: + printf("%s is now terrorist\n", player[id].name); + break; + case 2: + printf("%s is now counter-terrorist\n", player[id].name); + break; + default: + printf("%s joined a unknown team\n", player[id].name); + break; + } + SendHitMessage(id, id, 0, writesocket); + player[id].dead = 1; + RemoveAllPlayerWeapon(id); + } + if (team <= 2) + { + SendTeamChangeMessage(id, team, skin, writesocket); + } + return 0; } /* -int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) -Return Values: -0 - OK -1 - Don't move -*/ -int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) + int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) + Return Values: + 0 - OK + 1 - Don't move + */ +int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, + int writesocket) { - /* - int newx = (int)ceil((x)/32); - int newy = (int)ceil((y)/32); - printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); - */ - return 0; + /* + int newx = (int)ceil((x)/32); + int newy = (int)ceil((y)/32); + printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); + */ + return 0; }
Jermuk/custom_cs2dsrv
9be1d8045477fd9282ffc041740ca20c4a81cd5d
- Hopefully fixed player timeout
diff --git a/include/functions.h b/include/functions.h index 4f22c53..a575218 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,24 +1,24 @@ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); -void CheckForTimeout(void); +void CheckForTimeout(int writesocket); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(char *message, int id); void PaketConfirmation(char *message, int id, int writesocket); int CheckPlayerData(char *password); unsigned char *GetEncodedString(unsigned char *string, int length); void CheckAllPlayerForReload(int writesocket); extern time_t firsttime; #endif // FUNCTIONS_H_INCLUDED diff --git a/src/functions.c b/src/functions.c index 8128731..07dc304 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,419 +1,418 @@ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** - * \fn void CheckForTimeout(void) + * \fn void CheckForTimeout(int writesocket) * \brief check all player for timeout */ -void CheckForTimeout(void) +void CheckForTimeout(int writesocket) { int i; for (i = 1; i <= sv_maxplayers; i++) { - if (PlayerTimeout(i)) + if (player[i].used == 1 && PlayerTimeout(i)) { printf("Client %d timed out!\n", i); + SendLeaveMessage(i, writesocket); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * \note still not working * * TODO PlayerTimeout is still not working */ int PlayerTimeout(int id) { - id = 0; - /* + //id = 0; + time_t actualtime; time(&actualtime); - if(((player[id].lastpaket + TIMEOUT) > actualtime) && player[id].lastpaket != 0) + if(((player[id].lastpaket + TIMEOUT) < actualtime) && player[id].lastpaket != 0) { - printf("POSITIV!\n"); return 1; } - */ return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if(strcmp(sv_password, "")) { serverstatus += 1; } if(sv_usgnonly == 1) { serverstatus += 2; } if(sv_fow == 1) { serverstatus += 4; } if(sv_friendlyfire == 1) { serverstatus += 8; } if(1) //Same Version? { serverstatus += 16; } if(sv_gamemode != 0) { serverstatus += 32; } if(0) //LuaScripts { serverstatus += 64; } if(1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x>>8) | (*x<<8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 != 0) { if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if(*pTempNummer-1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer+1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(char *password) { if(strcmp(sv_password, password) != 0) { printf("Password wrong!\n"); return 1; } if(sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length+1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(void) * \brief check all player if their reload is ended * ,send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].reloading != 0) { if(player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if(player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } diff --git a/src/main.c b/src/main.c index 26a9dbf..c68bcb3 100644 --- a/src/main.c +++ b/src/main.c @@ -1,195 +1,195 @@ #include "../include/main.h" time_t firsttime; int main() { int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); time(&firsttime); while(1) { - CheckForTimeout(); + CheckForTimeout(readsocket); PingAllPlayer(readsocket); CheckAllPlayerForReload(readsocket); select(readsocket+1, &descriptor, NULL, NULL, NULL); if(FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); if(id != -1) { if (ValidatePaket(buffer, id)) { PaketConfirmation(buffer, id, readsocket); time(&player[id].lastpaket); int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; case 16: rtn = reload(message, tempsize, id, readsocket); break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return 0; } diff --git a/src/map.c b/src/map.c index 18f33b4..241d9ce 100644 --- a/src/map.c +++ b/src/map.c @@ -1,171 +1,171 @@ #include "../include/map.h" void ReadMap() { FILE *file; int i; tspawncount = 0; ctspawncount = 0; char *mappath = malloc(strlen(sv_map)+5); memcpy(mappath, sv_map, strlen(sv_map)); memcpy(mappath+strlen(sv_map), ".map\0", 5); file = fopen(mappath,"rb"); if(file == NULL) error_exit("Map not found.. Abort\n"); else printf("Loading '%s'..", mappath); free(mappath); //------------------------------ unsigned char *mapheader = ReadLine(file); for(i = 1; i <= 9; i++) ReadByte(file); for(i = 1; i <= 10; i++) ReadInt(file); for(i = 1; i <= 10; i++) ReadLine(file); unsigned char *code = ReadLine(file); unsigned char *tileset = ReadLine(file); unsigned char loaded = ReadByte(file); int maxx = ReadInt(file); int maxy = ReadInt(file); unsigned char *background = ReadLine(file); int backgroundx = ReadInt(file); int backgroundy = ReadInt(file); unsigned char red = ReadByte(file); unsigned char green = ReadByte(file); unsigned char blue = ReadByte(file); unsigned char *mapcheck = ReadLine(file); //----------------------------------------- unsigned char *tilemode = malloc(loaded+1); if(tilemode == NULL) error_exit("Memory error in ReadMap()\n"); for(i = 0; i <= loaded; i++) { tilemode[i] = ReadByte(file); } - map = malloc(maxx+1 * sizeof(struct TILE *)); + map = malloc(maxx * sizeof(struct TILE *)); if(map == NULL) error_exit("Memory error in ReadMap()\n"); for(i = 0; i <= maxx; i++) { - map[i] = malloc(maxy+1 * sizeof(struct TILE *)); + map[i] = malloc(maxy * sizeof(struct TILE *)); if(map[i] == NULL) error_exit("Memory error in ReadMap()\n"); int b; for(b = 0; b <= maxy; b++) { unsigned char bytecache = ReadByte(file); if (bytecache > loaded) { bytecache = 0; } map[i][b].tileid = bytecache; map[i][b].mode = tilemode[bytecache]; //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); } } //--------------------------------------- unsigned char enities_count = ReadByte(file); for(i = 0; i <= enities_count-1; i++) { unsigned char *name = ReadLine(file); unsigned char typ = ReadByte(file); int x = ReadInt(file); int y = ReadInt(file); unsigned char *trigger = ReadLine(file); //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); int b; for(b = 0; b <= 9; b++) { int unknownint = ReadInt(file); unsigned char *unknown = ReadLine(file); //eprintf("(%d) %s || ", unknownint, unknown); free(unknown); } switch(typ) { case 0: { tspawnx[tspawncount] = x; tspawny[tspawncount] = y; tspawncount++; break; } case 1: { ctspawnx[ctspawncount] = x; ctspawny[ctspawncount] = y; ctspawncount++; break; } default: { break; } } free(name); free(trigger); } fclose(file); eprintf("loaded!\n"); free(mapheader); free(code); free(tileset); free(background); free(mapcheck); } unsigned char *ReadLine(FILE *file) { int position = 0; char *line = NULL; char c; while( (c=fgetc(file)) != 13) { if(c == EOF) error_exit("EndOfFile in ReadByte()\n"); line = realloc(line, position+1); if(line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = c; position++; } line = realloc(line, position+1); if(line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = '\0'; position++; fgetc(file); //0x0A return line; } unsigned char ReadByte(FILE *file) { unsigned char byte = fgetc(file); if(byte == EOF) error_exit("EndOfFile in ReadByte()\n"); return byte; } int ReadInt(FILE *file) { unsigned char byte1 = fgetc(file); if(byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte2 = fgetc(file); if(byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte3 = fgetc(file); if(byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte4 = fgetc(file); if(byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/weapons.c b/src/weapons.c index 5e99d08..deedd50 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,45 +1,44 @@ #include "../include/weapons.h" void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime) { if(name != NULL) { weapons[id].name = malloc(strlen(name)+1); if(weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); strncpy(weapons[id].name, name, strlen(name)+1); } else { weapons[id].name = NULL; } weapons[id].weapondamage = wpndmg; weapons[id].weapondamage_z1 = wpndmg_z1; weapons[id].weapondamage_z2 = wpndmg_z2; weapons[id].freq = freq; weapons[id].speed = speed; weapons[id].slot = slot; weapons[id].price = price; weapons[id].range = range; weapons[id].accuracy = accuracy; weapons[id].ammo1 = ammo1; weapons[id].ammo2 = ammo2; weapons[id].reloadtime = reloadtime; } void WeaponInit() { int i; for(i = 0; i <= 99; i++) { AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0); } AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000); AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000); AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000); AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000); AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000); AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000); AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0); - //FIXME finish reload }
Jermuk/custom_cs2dsrv
ea6fb036f88b50dcc4365cee452cb3f0fbbc23fb
- Fixed "for" overflow
diff --git a/src/functions.c b/src/functions.c index 2166005..8128731 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,419 +1,419 @@ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(void) * \brief check all player for timeout */ void CheckForTimeout(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (PlayerTimeout(i)) { printf("Client %d timed out!\n", i); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * \note still not working * * TODO PlayerTimeout is still not working */ int PlayerTimeout(int id) { id = 0; /* time_t actualtime; time(&actualtime); if(((player[id].lastpaket + TIMEOUT) > actualtime) && player[id].lastpaket != 0) { printf("POSITIV!\n"); return 1; } */ return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if(strcmp(sv_password, "")) { serverstatus += 1; } if(sv_usgnonly == 1) { serverstatus += 2; } if(sv_fow == 1) { serverstatus += 4; } if(sv_friendlyfire == 1) { serverstatus += 8; } if(1) //Same Version? { serverstatus += 16; } if(sv_gamemode != 0) { serverstatus += 32; } if(0) //LuaScripts { serverstatus += 64; } if(1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x>>8) | (*x<<8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 != 0) { if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if(*pTempNummer-1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer+1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(char *password) { if(strcmp(sv_password, password) != 0) { printf("Password wrong!\n"); return 1; } if(sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length+1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; - for (i = 0; i <= length; i++) + for (i = 0; i <= length; i++) //length and not length-1 because malloc(length+1) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(void) * \brief check all player if their reload is ended * ,send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].reloading != 0) { if(player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if(player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } diff --git a/src/map.c b/src/map.c index 39e6a9d..18f33b4 100644 --- a/src/map.c +++ b/src/map.c @@ -1,171 +1,171 @@ #include "../include/map.h" void ReadMap() { FILE *file; int i; tspawncount = 0; ctspawncount = 0; char *mappath = malloc(strlen(sv_map)+5); memcpy(mappath, sv_map, strlen(sv_map)); memcpy(mappath+strlen(sv_map), ".map\0", 5); file = fopen(mappath,"rb"); if(file == NULL) error_exit("Map not found.. Abort\n"); else printf("Loading '%s'..", mappath); free(mappath); //------------------------------ unsigned char *mapheader = ReadLine(file); for(i = 1; i <= 9; i++) ReadByte(file); for(i = 1; i <= 10; i++) ReadInt(file); for(i = 1; i <= 10; i++) ReadLine(file); unsigned char *code = ReadLine(file); unsigned char *tileset = ReadLine(file); unsigned char loaded = ReadByte(file); int maxx = ReadInt(file); int maxy = ReadInt(file); unsigned char *background = ReadLine(file); int backgroundx = ReadInt(file); int backgroundy = ReadInt(file); unsigned char red = ReadByte(file); unsigned char green = ReadByte(file); unsigned char blue = ReadByte(file); unsigned char *mapcheck = ReadLine(file); //----------------------------------------- - unsigned char *tilemode = malloc(loaded); + unsigned char *tilemode = malloc(loaded+1); if(tilemode == NULL) error_exit("Memory error in ReadMap()\n"); for(i = 0; i <= loaded; i++) { tilemode[i] = ReadByte(file); } - map = malloc(maxx * sizeof(struct TILE *)); + map = malloc(maxx+1 * sizeof(struct TILE *)); if(map == NULL) error_exit("Memory error in ReadMap()\n"); for(i = 0; i <= maxx; i++) { - map[i] = malloc(maxy * sizeof(struct TILE *)); + map[i] = malloc(maxy+1 * sizeof(struct TILE *)); if(map[i] == NULL) error_exit("Memory error in ReadMap()\n"); int b; for(b = 0; b <= maxy; b++) { unsigned char bytecache = ReadByte(file); if (bytecache > loaded) { bytecache = 0; } map[i][b].tileid = bytecache; map[i][b].mode = tilemode[bytecache]; //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); } } //--------------------------------------- unsigned char enities_count = ReadByte(file); for(i = 0; i <= enities_count-1; i++) { unsigned char *name = ReadLine(file); unsigned char typ = ReadByte(file); int x = ReadInt(file); int y = ReadInt(file); unsigned char *trigger = ReadLine(file); //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); int b; for(b = 0; b <= 9; b++) { int unknownint = ReadInt(file); unsigned char *unknown = ReadLine(file); //eprintf("(%d) %s || ", unknownint, unknown); free(unknown); } switch(typ) { case 0: { tspawnx[tspawncount] = x; tspawny[tspawncount] = y; tspawncount++; break; } case 1: { ctspawnx[ctspawncount] = x; ctspawny[ctspawncount] = y; ctspawncount++; break; } default: { break; } } free(name); free(trigger); } fclose(file); eprintf("loaded!\n"); free(mapheader); free(code); free(tileset); free(background); free(mapcheck); } unsigned char *ReadLine(FILE *file) { int position = 0; char *line = NULL; char c; while( (c=fgetc(file)) != 13) { if(c == EOF) error_exit("EndOfFile in ReadByte()\n"); line = realloc(line, position+1); if(line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = c; position++; } line = realloc(line, position+1); if(line == NULL) error_exit("Memory error in ReadLine()\n"); line[position] = '\0'; position++; fgetc(file); //0x0A return line; } unsigned char ReadByte(FILE *file) { unsigned char byte = fgetc(file); if(byte == EOF) error_exit("EndOfFile in ReadByte()\n"); return byte; } int ReadInt(FILE *file) { unsigned char byte1 = fgetc(file); if(byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte2 = fgetc(file); if(byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte3 = fgetc(file); if(byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); unsigned char byte4 = fgetc(file); if(byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } diff --git a/src/pakets.c b/src/pakets.c index 84e4ec8..79de8db 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -1,1016 +1,1016 @@ #include "../include/pakets.h" int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) { int paketlength = length; int i; printf("Unknown packet: "); for(i = 2; i <= position-1; i++) { eprintf("%d-", buffer[i]); } eprintf("\n\t"); - for(i = 0; i <= length; i++) + for(i = 0; i <= length-1; i++) { eprintf("%d-", message[i]); } eprintf("\n"); return paketlength; } int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_unknown)!\n"); return length; } return paketlength; } int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_known)!\n"); return length; } return paketlength; } int ping_ingame(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; return paketlength; } int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch(OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnBuyAttempt(id, wpnid, writesocket)) { case 0: OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if(length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message+1, sizeof(float)); if(temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch(OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch(player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp]+0.5)*32; player[id].y = (tspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp]+0.5)*32; player[id].y = (ctspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch(OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if(skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer+2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if(length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + strlen(sv_name) + strlen(sv_map); if(sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch(message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if(sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if(length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch(message[1]) { case 0x00: { paketlength = 2; int i; - for (i = 1; i <= MAX_CLIENTS; i++) + for (i = 1; i <= MAX_CLIENTS-1; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if(paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch(OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength=4; unsigned char team, unknown; int paketsize; if(paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length-position+1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(string, message+position, paketsize); string[paketsize] = '\0'; position += paketsize; switch(OnChatMessage(id, string, team, writesocket)) { case 0: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch(message[1]) { case 0: { paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if(player[id].joinstatus == 1) { paketlength = 16; // ??? if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; player[id].name = malloc(stringsize); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message+position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; unsigned char *password = malloc(stringsize); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message+position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; for (i = 0; i <= strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; unsigned char *encryption1 = malloc(stringsize); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message+position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message+position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes /* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif */ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; player[id].spraylogo = malloc(stringsize); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message+position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; unsigned char *maphash= malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message+position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; player[id].win= malloc(stringsize); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message+position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; //printf("\tWIN: %s (%d)\n", player[id].win, strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch(tempstatus) { case 0x00: stringsize = 6 + strlen(sv_map) + strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); position += strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } //stringsize = 16 + strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if(stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if(player[id].joinstatus == 2) { int position = 2; paketlength = 5; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Map-Hash too big\n"); return length; } position++; unsigned char *maphash = malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message+position, stringsize); maphash[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMaphash: %s\n", maphash); //pre_authcode_respond stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("pre_authcon_respond too big\n"); return length; } position++; unsigned char *pre_authcode_respond = malloc(stringsize); if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(pre_authcode_respond, message+position, stringsize); pre_authcode_respond[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); //Player Version unsigned char mapstatus = message[position]; //avoid warning position++; //printf("\tMapstatus: %d\n", mapstatus); free(pre_authcode_respond); free(maphash); //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if(player[id].joinstatus == 3) { int position = 2; paketlength = 3; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Mapname too big\n"); return length; } position++; unsigned char *mapname = malloc(stringsize); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message+position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- stringsize = 28 + strlen(sv_map) + strlen(sv_name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = 0; //Unknown diff --git a/src/settings.c b/src/settings.c index 39b9384..a71bb4b 100644 --- a/src/settings.c +++ b/src/settings.c @@ -1,25 +1,25 @@ #include "../include/settings.h" unsigned char pre_authcode[] = "5TWs3Obv7"; unsigned char sv_name[] = "Alpha Custom CS2D Server"; unsigned char sv_map[] = "de_cs2d"; unsigned int sv_hostport = 1994; -unsigned short sv_maxplayers = 32; +unsigned short sv_maxplayers = 32 +1; unsigned short sv_fow = 0; unsigned short sv_gamemode = 2; unsigned short sv_friendlyfire = 0; unsigned short sv_usgnonly = 0; unsigned char sv_password[] = ""; unsigned short bot_count = 0; unsigned short mp_roundtime = 5; unsigned short mp_freezetime = 0; unsigned short mp_c4timer = 35; unsigned short mp_infammo = 0; unsigned short mp_respawndelay = 0; unsigned short mp_specmode = 1; unsigned short onlineplayer = 0; unsigned short mp_startmoney = 65000; char startweapons[] = {50};
Jermuk/custom_cs2dsrv
479e4cda5fcef5ce1fe4b22fe007845f749b441f
- Added ct buy support
diff --git a/src/script-functions.c b/src/script-functions.c index e123afe..86a0e12 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,369 +1,385 @@ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if(player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].actualweapon = i; player[id].zoommode = 0; //CHANGE there are also silencer, ... player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if(*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if(*ammo1 != -1) { *ammo1 = *ammo1-1; } } // TODO Firetimer does not work /* int temptime = mtime(); printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); if(temptime < player[id].firetimer) { printf("Firetimer error!"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; //printf("(Debug) %d\n", player[id].firetimer); } */ int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = {0}; if(temprot < 0) { temprot = 360 - (temprot *-1); } temprot = 360 - temprot; temprot += 90; if(temprot > 360) { temprot = temprot-360; } rotx = cos((temprot)*PI/180); roty = sin((temprot)*PI/180); for(i = 1; i <= range; i++) { startx += i*rotx; starty -= i*roty; int tilex = (int)(startx)/32; int tiley = (int)(starty)/32; if(tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if(tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for(b = 1; b <= sv_maxplayers; b++) { if(player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if(sqrt( (player[b].x - startx)*(player[b].x - startx) + (player[b].y - starty)*(player[b].y - starty) ) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch(player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if(player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { if(player[id].money - weapons[wpnid].price >= 0) { int i; for(i = 0; i <= 99; i++) { if(weapons[wpnid].freq != 0) //If weapon unknown -> everything is 0 { //Check if in buyzone if(player[id].team == 1) { int b; for(b = 0; b <= tspawncount; b++) { int playerx = player[id].x; int playery = player[id].y; int tempx = tspawnx[b]*32; int tempy = tspawny[b]*32; //If player in buyzone (5*5) if(playerx >= tempx-64 && playerx <= tempx+64 && playery >= tempy-64 && playery <= tempy+64) { return 0; } } } + else if(player[id].team == 2) + { + int b; + for(b = 0; b <= ctspawncount; b++) + { + int playerx = player[id].x; + int playery = player[id].y; + int tempx = ctspawnx[b]*32; + int tempy = ctspawny[b]*32; + //If player in buyzone (5*5) + if(playerx >= tempx-64 && playerx <= tempx+64 && playery >= tempy-64 && playery <= tempy+64) + { + return 0; + } + } + } } } } return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if(team == 1) { printf("%s: %s\n", player[id].name, message); } else if(team == 2) { printf("%s (Team): %s\n", player[id].name, message); } SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if(skin != 5) { switch(team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } } if(team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; }
Jermuk/custom_cs2dsrv
01df993a6cc1e62efb702d10a5cf252b06322da1
- LITTLE_ENDIAN removed
diff --git a/include/settings.h b/include/settings.h index c18b956..9fa6128 100644 --- a/include/settings.h +++ b/include/settings.h @@ -1,37 +1,36 @@ #ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #define MAX_BUF 1024 /* --- Server Settings --- */ #define LOCAL_PORT 1994 #define MAX_CLIENTS 64 #define TIMEOUT 10 -#define LITTLE_ENDIAN extern unsigned char pre_authcode[]; extern unsigned char sv_name[]; extern unsigned char sv_map[]; extern unsigned int sv_hostport; extern unsigned short sv_maxplayers; extern unsigned short sv_fow; extern unsigned short sv_gamemode; extern unsigned short sv_friendlyfire; extern unsigned short sv_usgnonly; extern unsigned char sv_password[]; extern unsigned short bot_count; extern unsigned short mp_roundtime; extern unsigned short mp_freezetime; extern unsigned short mp_c4timer; extern unsigned short mp_infammo; extern unsigned short mp_respawndelay; extern unsigned short mp_specmode; extern unsigned short onlineplayer; extern unsigned short mp_startmoney; #define STARTWEAPONS_COUNT 1 extern char startweapons[]; #endif // SETTINGS_H_INCLUDED diff --git a/src/pakets.c b/src/pakets.c index 7690ea3..84e4ec8 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -218,1028 +218,1029 @@ int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch(OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch(player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp]+0.5)*32; player[id].y = (tspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp]+0.5)*32; player[id].y = (ctspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch(OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if(skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer+2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if(length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + strlen(sv_name) + strlen(sv_map); if(sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch(message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if(sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if(length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch(message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if(paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch(OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength=4; unsigned char team, unknown; int paketsize; if(paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length-position+1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(string, message+position, paketsize); string[paketsize] = '\0'; position += paketsize; switch(OnChatMessage(id, string, team, writesocket)) { case 0: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } switch(message[1]) { case 0: { paketlength = 2; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } break; } case 1: { if(player[id].joinstatus == 1) { paketlength = 16; // ??? if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } int position = 2; //Playername int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Playername too big\n"); return length; } paketlength += stringsize; position++; player[id].name = malloc(stringsize); if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].name, message+position, stringsize); player[id].name[stringsize] = '\0'; position += stringsize; //+1 because after it there is a null byte, so ignore it //printf("Player %s connected..\n", player[id].name); stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Password too big\n"); return length; } paketlength += stringsize; position++; unsigned char *password = malloc(stringsize); if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(password, message+position, stringsize); password[stringsize] = '\0'; position += stringsize; //printf("\tPassword: "); /* int i; for (i = 0; i <= strlen(password); i++) { printf("%d-", password[i]); } printf("\n"); */ //Encryption String stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Encryption too big\n"); return length; } paketlength += stringsize; position++; unsigned char *encryption1 = malloc(stringsize); if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(encryption1, message+position, stringsize); encryption1[stringsize] = '\0'; position += stringsize; //printf("\tEncryptionstring: %s\n", encryption1); //Player Version player[id].version = message[position]; position++; //printf("\tVersion: %d\n", player[id].version); position++; //Null-byte //USGN ID player[id].usgn = malloc(sizeof(unsigned short)); if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].usgn, message+position, 2); //sizeof(unsigned short) == 2 position += 4; //2 bytes + 2 null bytes -#ifdef LITTLE_ENDIAN +/* #else *player[id].usgn = endian_swap_short(player[id].usgn); #endif +*/ //printf("\tUSGN-ID: %u\n", *player[id].usgn); //Spraylogo stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Spraylogoname too big\n"); return length; }; paketlength += stringsize; position++; player[id].spraylogo = malloc(stringsize); if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].spraylogo, message+position, stringsize); player[id].spraylogo[stringsize] = '\0'; position += stringsize; //printf("\tSpraylogo: %s\n", player[id].spraylogo); //Map-Hash stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Map-Hash too big\n"); return length; } paketlength += stringsize; position++; unsigned char *maphash= malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message+position, stringsize); maphash[stringsize] = '\0'; position += stringsize; //printf("\tMap-Hash: %s\n", maphash); position++; //Nullbyte //WIN stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("WIN too big\n"); return length; } paketlength += stringsize; position++; player[id].win= malloc(stringsize); if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(player[id].win, message+position, stringsize); player[id].win[stringsize] = '\0'; position += stringsize; //printf("\tWIN: %s (%d)\n", player[id].win, strlen(player[id].win)); unsigned char *buffer = NULL; stringsize = 0; int tempstatus = CheckPlayerData(password); switch(tempstatus) { case 0x00: stringsize = 6 + strlen(sv_map) + strlen(pre_authcode); buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = 0; //Normal position++; buffer[position] = id; position++; buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); position += strlen(pre_authcode); player[id].joinstatus = 2; break; default: { stringsize = 3; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 2; position++; buffer[position] = tempstatus; //Everyone is banned (just for testing) position++; player[id].joinstatus = 0; break; } } //stringsize = 16 + strlen(sv_map); /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ if(stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); free(encryption1); free(maphash); free(buffer); onlineplayer++; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 3: { if(player[id].joinstatus == 2) { int position = 2; paketlength = 5; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Map-Hash too big\n"); return length; } position++; unsigned char *maphash = malloc(stringsize); if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(maphash, message+position, stringsize); maphash[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMaphash: %s\n", maphash); //pre_authcode_respond stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("pre_authcon_respond too big\n"); return length; } position++; unsigned char *pre_authcode_respond = malloc(stringsize); if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(pre_authcode_respond, message+position, stringsize); pre_authcode_respond[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); //Player Version unsigned char mapstatus = message[position]; //avoid warning position++; //printf("\tMapstatus: %d\n", mapstatus); free(pre_authcode_respond); free(maphash); //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if(player[id].joinstatus == 3) { int position = 2; paketlength = 3; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Mapname too big\n"); return length; } position++; unsigned char *mapname = malloc(stringsize); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message+position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- stringsize = 28 + strlen(sv_map) + strlen(sv_name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_friendlyfire; position++; buffer[position] = 0; //Unknown position++; buffer[position] = mp_roundtime; position++; buffer[position] = mp_freezetime; position++; buffer[position] = mp_c4timer; position++; buffer[position] = 32; //Unknown position++; buffer[position] = 124; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 1; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_maxplayers; position++; buffer[position] = sv_fow; position++; buffer[position] = mp_specmode; position++; buffer[position] = sv_gamemode; position++; buffer[position] = mp_respawndelay; position++; buffer[position] = mp_infammo; position++; buffer[position] = 3; //strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; position++; buffer[position] = onlineplayer; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 1 && i != id) { unsigned char *encodedname; encodedname = GetEncodedString(player[i].name, strlen(player[i].name)); unsigned short *deaths = &player[i].deaths; unsigned short tempscore = player[i].deaths + 1000; unsigned short *score = &tempscore; unsigned short tempx = (player[i].x); unsigned short tempy = (player[i].y); unsigned short *x = &tempx; unsigned short *y = &tempy; float *ptemprotation = &player[i].rotation; int playersize = 25 + strlen(encodedname); buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = i; position++; buffer[position] = strlen(encodedname); position++; memcpy(buffer+position, encodedname, strlen(encodedname)); position += strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[i].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; /* buffer[position] = score[0]; //Deaths position++; buffer[position] = score[1]; //Deaths position++; */ memcpy(buffer+position, score, 2); position += 2; /* buffer[position] = deaths[0]; //Deaths position++; buffer[position] = deaths[1]; //Deaths position++; */ memcpy(buffer+position, deaths, 2); position += 2; memcpy(buffer+position, x, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; memcpy(buffer+position, y, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = ptemprotation[0]; //Rotation position++; buffer[position] = ptemprotation[1]; //Rotation position++; buffer[position] = player[i].health; //Health position++; buffer[position] = player[i].armor; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe position++; buffer[position] = 0; //Unknown position++; /* 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 e8 03 00 00 12 01 00 00 01 03 e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 */ } } if(1) { unsigned char *encodedname; encodedname = GetEncodedString(player[id].name, strlen(player[id].name)); int playersize = 25 + strlen(encodedname); buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = id; position++; buffer[position] = strlen(encodedname); position++; memcpy(buffer+position, encodedname, strlen(encodedname)); position += strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[id].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 232; //Unknown position++; buffer[position] = 3; //Unknown position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //X position++; buffer[position] = 0; //X position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Health position++; buffer[position] = 0; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Aktuelle Waffe 50 = Knife position++; buffer[position] = 0; //Unknown position++; } SendToPlayer(buffer, position, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4;
Jermuk/custom_cs2dsrv
56a0fcd8ebb5dac0b7d6e6fd85967208be8fb16a
- Disabled log for non-windows system (Segmentation fault)
diff --git a/.cproject b/.cproject index 580450d..4a8405e 100644 --- a/.cproject +++ b/.cproject @@ -1,604 +1,628 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <?fileVersion 4.0.0?> <cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage"> <storageModule moduleId="org.eclipse.cdt.core.settings"> <cconfiguration id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458"> <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458" moduleId="org.eclipse.cdt.core.settings" name="Debug"> <externalSettings/> <extensions> <extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/> <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> </extensions> </storageModule> <storageModule moduleId="cdtBuildSystem" version="4.0.0"> <configuration artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.exe" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.exe" cleanCommand="rm -rf" description="" id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458" name="Debug" parent="cdt.managedbuild.config.gnu.mingw.exe.debug"> <folderInfo id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458." name="/" resourcePath=""> <toolChain id="cdt.managedbuild.toolchain.gnu.mingw.exe.debug.1188392895" name="MinGW GCC" superClass="cdt.managedbuild.toolchain.gnu.mingw.exe.debug"> <targetPlatform id="cdt.managedbuild.target.gnu.platform.mingw.exe.debug.433122987" name="Debug Platform" superClass="cdt.managedbuild.target.gnu.platform.mingw.exe.debug"/> <builder buildPath="${workspace_loc:/custom_cs2dsrv/Debug}" id="cdt.managedbuild.tool.gnu.builder.mingw.base.442254957" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="CDT Internal Builder" superClass="cdt.managedbuild.tool.gnu.builder.mingw.base"/> <tool id="cdt.managedbuild.tool.gnu.assembler.mingw.exe.debug.172730339" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.mingw.exe.debug"> <inputType id="cdt.managedbuild.tool.gnu.assembler.input.671771288" superClass="cdt.managedbuild.tool.gnu.assembler.input"/> </tool> <tool id="cdt.managedbuild.tool.gnu.archiver.mingw.base.452536062" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.mingw.base"/> <tool id="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.debug.1125479542" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.debug"> <option id="gnu.cpp.compiler.mingw.exe.debug.option.optimization.level.856167253" name="Optimization Level" superClass="gnu.cpp.compiler.mingw.exe.debug.option.optimization.level" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/> <option id="gnu.cpp.compiler.mingw.exe.debug.option.debugging.level.1286427477" name="Debug Level" superClass="gnu.cpp.compiler.mingw.exe.debug.option.debugging.level" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/> </tool> <tool id="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug"> <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.mingw.exe.debug.option.optimization.level.899548284" name="Optimization Level" superClass="gnu.c.compiler.mingw.exe.debug.option.optimization.level" valueType="enumerated"/> <option id="gnu.c.compiler.mingw.exe.debug.option.debugging.level.218260318" name="Debug Level" superClass="gnu.c.compiler.mingw.exe.debug.option.debugging.level" value="gnu.c.debugging.level.max" valueType="enumerated"/> <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.293456763" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/> </tool> <tool id="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.debug.237306527" name="MinGW C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.debug"> <option id="gnu.c.link.option.libs.696325141" name="Libraries (-l)" superClass="gnu.c.link.option.libs" valueType="libs"> <listOptionValue builtIn="false" value="wsock32"/> </option> <option id="gnu.c.link.option.paths.1944619386" name="Library search path (-L)" superClass="gnu.c.link.option.paths" valueType="libPaths"> <listOptionValue builtIn="false" value="&quot;C:\MinGW32\lib\&quot;"/> </option> <inputType id="cdt.managedbuild.tool.gnu.c.linker.input.1057549252" superClass="cdt.managedbuild.tool.gnu.c.linker.input"> <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> <additionalInput kind="additionalinput" paths="$(LIBS)"/> </inputType> </tool> <tool id="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.debug.715096099" name="MinGW C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.debug"/> </toolChain> </folderInfo> </configuration> </storageModule> <storageModule moduleId="scannerConfiguration"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="makefileGenerator"> <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827;cdt.managedbuild.config.gnu.mingw.exe.release.1594405827.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424;cdt.managedbuild.tool.gnu.c.compiler.input.191950135"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="makefileGenerator"> <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> </scannerConfigBuildInfo> <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458;cdt.managedbuild.config.gnu.mingw.exe.debug.133679458.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703;cdt.managedbuild.tool.gnu.c.compiler.input.293456763"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="makefileGenerator"> <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> </scannerConfigBuildInfo> </storageModule> <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> + <storageModule moduleId="org.eclipse.cdt.make.core.buildtargets"> + <buildTargets> + <target name="cs2dsrv" path="src" targetID="org.eclipse.cdt.build.MakeTargetBuilder"> + <buildCommand>make</buildCommand> + <buildArguments/> + <buildTarget>cs2dsrv</buildTarget> + <stopOnError>true</stopOnError> + <useDefaultCommand>true</useDefaultCommand> + <runAllBuilders>true</runAllBuilders> + </target> + </buildTargets> + </storageModule> </cconfiguration> <cconfiguration id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827"> <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827" moduleId="org.eclipse.cdt.core.settings" name="Release"> <externalSettings/> <extensions> <extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/> <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> </extensions> </storageModule> <storageModule moduleId="cdtBuildSystem" version="4.0.0"> <configuration artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.exe" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.exe" cleanCommand="rm -rf" description="" id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827" name="Release" parent="cdt.managedbuild.config.gnu.mingw.exe.release"> <folderInfo id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827." name="/" resourcePath=""> <toolChain id="cdt.managedbuild.toolchain.gnu.mingw.exe.release.1830096364" name="MinGW GCC" superClass="cdt.managedbuild.toolchain.gnu.mingw.exe.release"> <targetPlatform id="cdt.managedbuild.target.gnu.platform.mingw.exe.release.199043754" name="Debug Platform" superClass="cdt.managedbuild.target.gnu.platform.mingw.exe.release"/> <builder buildPath="${workspace_loc:/custom_cs2dsrv/Release}" id="cdt.managedbuild.tool.gnu.builder.mingw.base.781603840" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="CDT Internal Builder" superClass="cdt.managedbuild.tool.gnu.builder.mingw.base"/> <tool id="cdt.managedbuild.tool.gnu.assembler.mingw.exe.release.1948519560" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.mingw.exe.release"> <inputType id="cdt.managedbuild.tool.gnu.assembler.input.455298474" superClass="cdt.managedbuild.tool.gnu.assembler.input"/> </tool> <tool id="cdt.managedbuild.tool.gnu.archiver.mingw.base.884564668" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.mingw.base"/> <tool id="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.release.629144444" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.release"> <option id="gnu.cpp.compiler.mingw.exe.release.option.optimization.level.1969272803" name="Optimization Level" superClass="gnu.cpp.compiler.mingw.exe.release.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/> <option id="gnu.cpp.compiler.mingw.exe.release.option.debugging.level.22968446" name="Debug Level" superClass="gnu.cpp.compiler.mingw.exe.release.option.debugging.level" value="gnu.cpp.compiler.debugging.level.none" valueType="enumerated"/> </tool> <tool id="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release"> <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.mingw.exe.release.option.optimization.level.1005366988" name="Optimization Level" superClass="gnu.c.compiler.mingw.exe.release.option.optimization.level" valueType="enumerated"/> <option id="gnu.c.compiler.mingw.exe.release.option.debugging.level.180917112" name="Debug Level" superClass="gnu.c.compiler.mingw.exe.release.option.debugging.level" value="gnu.c.debugging.level.none" valueType="enumerated"/> <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.191950135" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/> </tool> <tool id="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.release.376579228" name="MinGW C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.release"> <option id="gnu.c.link.option.libs.879542908" name="Libraries (-l)" superClass="gnu.c.link.option.libs" valueType="libs"> <listOptionValue builtIn="false" value="wsock32"/> </option> <option id="gnu.c.link.option.paths.599340942" name="Library search path (-L)" superClass="gnu.c.link.option.paths" valueType="libPaths"> <listOptionValue builtIn="false" value="&quot;C:\MinGW32\lib\&quot;"/> </option> <inputType id="cdt.managedbuild.tool.gnu.c.linker.input.465269045" superClass="cdt.managedbuild.tool.gnu.c.linker.input"> <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> <additionalInput kind="additionalinput" paths="$(LIBS)"/> </inputType> </tool> <tool id="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.release.963626972" name="MinGW C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.release"/> </toolChain> </folderInfo> </configuration> </storageModule> <storageModule moduleId="scannerConfiguration"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="makefileGenerator"> <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827;cdt.managedbuild.config.gnu.mingw.exe.release.1594405827.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424;cdt.managedbuild.tool.gnu.c.compiler.input.191950135"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="makefileGenerator"> <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> </scannerConfigBuildInfo> <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458;cdt.managedbuild.config.gnu.mingw.exe.debug.133679458.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703;cdt.managedbuild.tool.gnu.c.compiler.input.293456763"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="makefileGenerator"> <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> <buildOutputProvider> <openAction enabled="true" filePath=""/> <parser enabled="true"/> </buildOutputProvider> <scannerInfoProvider id="specsFile"> <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> <parser enabled="true"/> </scannerInfoProvider> </profile> </scannerConfigBuildInfo> </storageModule> <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> + <storageModule moduleId="org.eclipse.cdt.make.core.buildtargets"> + <buildTargets> + <target name="cs2dsrv" path="src" targetID="org.eclipse.cdt.build.MakeTargetBuilder"> + <buildCommand>make</buildCommand> + <buildArguments/> + <buildTarget>cs2dsrv</buildTarget> + <stopOnError>true</stopOnError> + <useDefaultCommand>true</useDefaultCommand> + <runAllBuilders>true</runAllBuilders> + </target> + </buildTargets> + </storageModule> </cconfiguration> </storageModule> <storageModule moduleId="cdtBuildSystem" version="4.0.0"> <project id="custom_cs2dsrv.cdt.managedbuild.target.gnu.mingw.exe.750583817" name="Executable" projectType="cdt.managedbuild.target.gnu.mingw.exe"/> </storageModule> </cproject> diff --git a/log.txt b/log.txt index e69de29..27f7863 100644 --- a/log.txt +++ b/log.txt @@ -0,0 +1,36 @@ +TARGET := ./program +CXXFLAGS := -g -Wextra -Wall -Wno-long-long -pedantic-errors -std=c++98 +CXX := g++ +LIBS := +EXT := cpp +BUILDDIR := build + +override BUILDDIR := $(strip $(BUILDDIR)) +SOURCES := $(wildcard *.$(EXT)) +OBJECTS := $(patsubst %.$(EXT), $(BUILDDIR)/%.o, $(SOURCES)) +DEPS := $(patsubst %.$(EXT), $(BUILDDIR)/%.dep, $(SOURCES)) + +.PHONY: all +all: $(TARGET) + +$(TARGET): $(OBJECTS) $(DEPS) + $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJECTS) $(LIBS) + +ifneq ($(MAKECMDGOALS), clean) +-include $(DEPS) +endif + +$(OBJECTS): $(BUILDDIR)/%.o: %.$(EXT) $(BUILDDIR)/%.dep $(BUILDDIR)/.tag + $(CXX) $(CXXFLAGS) -c $< -o $@ + +$(DEPS): $(BUILDDIR)/%.dep: %.$(EXT) $(BUILDDIR)/.tag + mkdir -p $(dir $(@)) + $(CXX) $(CXXFLAGS) -MM $< -MT $@ -MT $(<:.$(EXT)=.o) -o $@ + +%.tag: + mkdir -p $(dir $(@)) + touch $@ + +.PHONY: clean +clean: + rm -rf $(BUILDDIR) \ No newline at end of file diff --git a/makefile b/makefile new file mode 100644 index 0000000..884bd97 --- /dev/null +++ b/makefile @@ -0,0 +1,2 @@ +all: + gcc -lm src/cross_layer.c src/main.c src/respond_messages.c src/settings.c src/functions.c src/map.c src/script-functions.c src/weapons.c src/log.c src/pakets.c src/sendto_functions.c -o custom_cs2dsrv \ No newline at end of file diff --git a/src/log.c b/src/log.c index 9a90a6a..b4c3446 100644 --- a/src/log.c +++ b/src/log.c @@ -1,49 +1,69 @@ #include "../include/log.h" void myprintf(char *string, ...) { +#ifdef _WIN32 FILE *logfile; time_t rawtime; struct tm * timeinfo; logfile = fopen("log.txt","a+"); if(logfile != NULL) { time(&rawtime); timeinfo = localtime(&rawtime); - fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + //fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); - vfprintf(logfile, string, argzeiger); + //vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } +#else + time_t rawtime; + struct tm * timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string,argzeiger); + va_end(argzeiger); +#endif } void myprintf2(char *string, ...) { +#ifdef _WIN32 FILE *logfile; logfile = fopen("log.txt","a+"); if(logfile != NULL) { va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } +#else + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string,argzeiger); + va_end(argzeiger); +#endif }
Jermuk/custom_cs2dsrv
7c5cd22ac4a2cbce3db1545efd16636729715738
- Added buyzone support
diff --git a/src/functions.c b/src/functions.c index 3b076fd..2166005 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,419 +1,419 @@ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; player[id].reloading = 0; player[id].reloadtimer = 0; int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(void) * \brief check all player for timeout */ void CheckForTimeout(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (PlayerTimeout(i)) { printf("Client %d timed out!\n", i); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * \note still not working * * TODO PlayerTimeout is still not working */ int PlayerTimeout(int id) { id = 0; /* time_t actualtime; time(&actualtime); if(((player[id].lastpaket + TIMEOUT) > actualtime) && player[id].lastpaket != 0) { printf("POSITIV!\n"); return 1; } */ return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if(strcmp(sv_password, "")) { serverstatus += 1; } if(sv_usgnonly == 1) { serverstatus += 2; } if(sv_fow == 1) { serverstatus += 4; } if(sv_friendlyfire == 1) { serverstatus += 8; } if(1) //Same Version? { serverstatus += 16; } if(sv_gamemode != 0) { serverstatus += 32; } if(0) //LuaScripts { serverstatus += 64; } if(1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x>>8) | (*x<<8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 != 0) { if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if(*pTempNummer-1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer+1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(char *password) { if(strcmp(sv_password, password) != 0) { printf("Password wrong!\n"); return 1; } if(sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length+1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } /** * \fn void CheckAllPlayerForReload(void) * \brief check all player if their reload is ended * ,send message if necessary, and rise their magazine */ void CheckAllPlayerForReload(int writesocket) { int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].reloading != 0) { - if(player[i].reloadtimer >= mtime()) + if(player[i].reloadtimer <= mtime()) { SendReloadMessage(i, 2, writesocket); if(player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) { player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; } else { player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; } player[i].reloading = 0; } } } } diff --git a/src/script-functions.c b/src/script-functions.c index f12ce21..e123afe 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,353 +1,369 @@ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if(player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].actualweapon = i; player[id].zoommode = 0; //CHANGE there are also silencer, ... player[id].reloading = 0; printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if(*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if(*ammo1 != -1) { *ammo1 = *ammo1-1; } } // TODO Firetimer does not work /* int temptime = mtime(); printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); if(temptime < player[id].firetimer) { printf("Firetimer error!"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; //printf("(Debug) %d\n", player[id].firetimer); } */ int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = {0}; if(temprot < 0) { temprot = 360 - (temprot *-1); } temprot = 360 - temprot; temprot += 90; if(temprot > 360) { temprot = temprot-360; } rotx = cos((temprot)*PI/180); roty = sin((temprot)*PI/180); for(i = 1; i <= range; i++) { startx += i*rotx; starty -= i*roty; int tilex = (int)(startx)/32; int tiley = (int)(starty)/32; if(tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if(tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for(b = 1; b <= sv_maxplayers; b++) { if(player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if(sqrt( (player[b].x - startx)*(player[b].x - startx) + (player[b].y - starty)*(player[b].y - starty) ) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch(player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if(player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { if(player[id].money - weapons[wpnid].price >= 0) { int i; for(i = 0; i <= 99; i++) { - if(weapons[wpnid].freq != 0) //If unknown everything is 0 + if(weapons[wpnid].freq != 0) //If weapon unknown -> everything is 0 { - return 0; + //Check if in buyzone + if(player[id].team == 1) + { + int b; + for(b = 0; b <= tspawncount; b++) + { + int playerx = player[id].x; + int playery = player[id].y; + int tempx = tspawnx[b]*32; + int tempy = tspawny[b]*32; + //If player in buyzone (5*5) + if(playerx >= tempx-64 && playerx <= tempx+64 && playery >= tempy-64 && playery <= tempy+64) + { + return 0; + } + } + } } } } return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; player[hitter].score++; player[hitter].kills++; player[victim].deaths++; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if(team == 1) { printf("%s: %s\n", player[id].name, message); } else if(team == 2) { printf("%s (Team): %s\n", player[id].name, message); } SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if(skin != 5) { switch(team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } } if(team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } diff --git a/src/weapons.c b/src/weapons.c index c43c240..5e99d08 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,45 +1,45 @@ #include "../include/weapons.h" void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime) { if(name != NULL) { weapons[id].name = malloc(strlen(name)+1); if(weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); strncpy(weapons[id].name, name, strlen(name)+1); } else { weapons[id].name = NULL; } weapons[id].weapondamage = wpndmg; weapons[id].weapondamage_z1 = wpndmg_z1; weapons[id].weapondamage_z2 = wpndmg_z2; weapons[id].freq = freq; weapons[id].speed = speed; weapons[id].slot = slot; weapons[id].price = price; weapons[id].range = range; weapons[id].accuracy = accuracy; weapons[id].ammo1 = ammo1; weapons[id].ammo2 = ammo2; weapons[id].reloadtime = reloadtime; } void WeaponInit() { int i; for(i = 0; i <= 99; i++) { AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0); } - AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 10000); - AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 10000); - AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 10000); - AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 10000); - AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 10000); - AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 10000); - AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 10000); + AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 1000); + AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 1000); + AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 1000); + AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 1000); + AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 1000); + AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 2000); + AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 0); //FIXME finish reload }
Jermuk/custom_cs2dsrv
3bb78a7393d9ecefa129d7e85cca357f135bcd8e
- Added Reload Support (Experimental) - All pistols added
diff --git a/include/functions.h b/include/functions.h index dde10f8..4f22c53 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,23 +1,24 @@ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(void); int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(char *message, int id); void PaketConfirmation(char *message, int id, int writesocket); int CheckPlayerData(char *password); unsigned char *GetEncodedString(unsigned char *string, int length); +void CheckAllPlayerForReload(int writesocket); extern time_t firsttime; #endif // FUNCTIONS_H_INCLUDED diff --git a/include/pakets.h b/include/pakets.h index 679a9d5..5eab215 100644 --- a/include/pakets.h +++ b/include/pakets.h @@ -1,28 +1,29 @@ #ifndef PAKETS_H_INCLUDED #define PAKETS_H_INCLUDED #include "main.h" int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position); int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id); int ping_ingame(unsigned char *message, int length, int id, int writesocket); int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); int confirmation_known(unsigned char *message, int length, int id, int writesocket); int fire(unsigned char *message, int length, int id, int writesocket); int buy(unsigned char *message, int length, int id, int writesocket); int rotupdate(unsigned char *message, int length, int id, int writesocket); int posupdatewalk(unsigned char *message, int length, int id, int writesocket); int posupdaterun(unsigned char *message, int length, int id, int writesocket); int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket); int posrotupdaterun(unsigned char *message, int length, int id, int writesocket); int respawnrequest(unsigned char *message, int length, int id, int writesocket); int weaponchange(unsigned char *message, int length, int id, int writesocket); int teamchange(unsigned char *message, int length, int id, int writesocket); int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); int specpos(unsigned char *message, int length, int id, int writesocket); int chatmessage(unsigned char *message, int length, int id, int writesocket); int joinroutine_known(unsigned char *message, int length, int id, int writesocket); int leave(int id, int writesocket); +int reload(unsigned char *message, int length, int id, int writesocket); #endif // PAKETS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h index 0101f42..9f5247f 100644 --- a/include/respond_messages.h +++ b/include/respond_messages.h @@ -1,22 +1,22 @@ #ifndef RESPOND_MESSAGES_H_INCLUDED #define RESPOND_MESSAGES_H_INCLUDED #include "main.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); void SendFireMessage(int id, int writesocket); void SendBuyMessage(int id, int wpnid, int writesocket); void SendHitMessage(int id, int victim, int health, int writesocket); void SendWeaponChangeMessage(int id, int wpnid, int writesocket); void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); void SendRotUpdate(int id, float rotation, int writesocket); void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket); void SendMessageToAll(unsigned char *message, int status, int writesocket); void SendJoinMessage(int id, int writesocket); void SendLeaveMessage(int id, int writesocket); void SendChatMessage(int id, unsigned char *message, int team, int writesocket); void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); void PingAllPlayer(int writesocket); - +void SendReloadMessage(int id, int status, int writesocket); #endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/structs.h b/include/structs.h index 71cd4be..99ffec1 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,73 +1,75 @@ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; float freq; short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; }; struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; }; struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; time_t lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; short deaths, score; unsigned short x,y; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; + unsigned short kills; + int reloadtimer, reloading; short dead; int start; int latency; int firetimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/include/weapons.h b/include/weapons.h index dc3e39c..c305899 100644 --- a/include/weapons.h +++ b/include/weapons.h @@ -1,10 +1,10 @@ #ifndef WEAPONS_H_INCLUDED #define WEAPONS_H_INCLUDED #include "main.h" -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2); +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime); void WeaponInit(); struct WEAPON weapons[100]; #endif // WEAPONS_H_INCLUDED diff --git a/src/functions.c b/src/functions.c index 3d96763..3b076fd 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,388 +1,419 @@ #include "../include/functions.h" /** * \fn int IsPlayerKnown(struct in_addr ip, u_short port) * \brief checks if a player is already known * \param ip client's ip * \param port client's port * \return the playerid or 0 if not found */ int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } /** * \fn void ClearPlayer(int id) * \brief clear all player variables */ void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; + player[id].reloading = 0; + player[id].reloadtimer = 0; int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } /** * \fn void ClearAllPlayer(void) * \brief clear all player variables */ void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } /** * \fn void CheckForTimeout(void) * \brief check all player for timeout */ void CheckForTimeout(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (PlayerTimeout(i)) { printf("Client %d timed out!\n", i); ClearPlayer(i); } } } /** * \fn int GivePlayerWeapon(int id, int wpnid) * \brief adds an specific weapon to a player * \param id player-id * \param wpnid weapon-id * \return the slot-id or 0 if not found */ int GivePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; return i; } } return 0; } /** * \fn void RemovePlayerWeapon(int id, int wpnid) * \brief removes an specific weapon to a player * \param id player-id * \param wpnid weapon-id */ void RemovePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } /** * \fn void RemoveAllPlayerWeapon(int id) * \brief remove all weapons from a player * \param id player-id */ void RemoveAllPlayerWeapon(int id) { int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; } } /** * \fn int PlayerTimeout(int id) * \brief checks if a specific player is timeout * \param id player-id * \return 1 - timeout; 0 - success * \note still not working * - * TODO Still not working + * TODO PlayerTimeout is still not working */ int PlayerTimeout(int id) { id = 0; /* time_t actualtime; time(&actualtime); if(((player[id].lastpaket + TIMEOUT) > actualtime) && player[id].lastpaket != 0) { printf("POSITIV!\n"); return 1; } */ return 0; } /** * \fn unsigned short GetServerStatus(void) * \brief needs for serverlist * \return serverstatus */ unsigned short GetServerStatus(void) { unsigned short serverstatus = 0; if(strcmp(sv_password, "")) { serverstatus += 1; } if(sv_usgnonly == 1) { serverstatus += 2; } if(sv_fow == 1) { serverstatus += 4; } if(sv_friendlyfire == 1) { serverstatus += 8; } if(1) //Same Version? { serverstatus += 16; } if(sv_gamemode != 0) { serverstatus += 32; } if(0) //LuaScripts { serverstatus += 64; } if(1) //Dedicated { serverstatus += 128; } return serverstatus; } /** * \fn unsigned short endian_swap_short(unsigned short *x) * \brief swap the endian for a short * \param *x pointer to an unsigned short * \return the endian-changed unsigned short */ unsigned short endian_swap_short(unsigned short *x) { *x = (*x>>8) | (*x<<8); return *x; } /** * \fn unsigned int endian_swap_int(unsigned int *x) * \brief swap the endian for an int * \param *x pointer to an int * \return the endian-changed int */ unsigned int endian_swap_int(unsigned int *x) { *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24); return *x; } /** * \fn int ValidatePaket(char *message, int id) * \brief validate if the first two bytes follow the numbering for a player and rise them if necessary * \param *message pointer to the message * \param id player-id * \return 0 if invalid; 1 if valid */ int ValidatePaket(char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 != 0) { if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if(*pTempNummer-1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } /** * \fn void PaketConfirmation(char *message, int id, int writesocket) * \brief sends an confirmation to a player if necessary * \param *message pointer to the message * \param id player-id */ void PaketConfirmation(char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer+1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } /** * \fn int CheckPlayerData(char *password) * \brief check all player data and looks if he/she can join * \param *password pointer to the password * \return the error number or 0 */ int CheckPlayerData(char *password) { if(strcmp(sv_password, password) != 0) { printf("Password wrong!\n"); return 1; } if(sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Different map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } /** * \fn unsigned char *GetEncodedString(unsigned char *string, int length) * \brief convert the playername into cs2d format * \param *string playername * \param length length from playername * \return the converted name */ unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length+1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } +/** + * \fn void CheckAllPlayerForReload(void) + * \brief check all player if their reload is ended + * ,send message if necessary, and rise their magazine + */ +void CheckAllPlayerForReload(int writesocket) +{ + int i; + for(i = 1; i <= sv_maxplayers; i++) + { + if(player[i].reloading != 0) + { + if(player[i].reloadtimer >= mtime()) + { + SendReloadMessage(i, 2, writesocket); + if(player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1 > 0) + { + player[i].slot[player[i].reloading].ammo2 -= player[i].slot[player[i].reloading].ammo1; + player[i].slot[player[i].reloading].ammo1 = weapons[player[i].slot[player[i].reloading].id].ammo1; + } + else + { + player[i].slot[player[i].reloading].ammo1 = player[i].slot[player[i].reloading].ammo2; + } + player[i].reloading = 0; + } + } + } +} diff --git a/src/main.c b/src/main.c index e94c748..26a9dbf 100644 --- a/src/main.c +++ b/src/main.c @@ -1,191 +1,195 @@ #include "../include/main.h" time_t firsttime; int main() { int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); time(&firsttime); while(1) { CheckForTimeout(); PingAllPlayer(readsocket); + CheckAllPlayerForReload(readsocket); select(readsocket+1, &descriptor, NULL, NULL, NULL); if(FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); if(id != -1) { if (ValidatePaket(buffer, id)) { PaketConfirmation(buffer, id, readsocket); time(&player[id].lastpaket); int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; + case 16: + rtn = reload(message, tempsize, id, readsocket); + break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 23: rtn = buy(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return 0; } diff --git a/src/pakets.c b/src/pakets.c index 8c5fa1b..7690ea3 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -935,512 +935,536 @@ int joinroutine_known(unsigned char *message, int length, int id, int writesocke //Respond stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 4; position++; buffer[position] = 0; //CheckPlayerData() position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); player[id].joinstatus = 3; } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } case 5: { if(player[id].joinstatus == 3) { int position = 2; paketlength = 3; if(paketlength > length) { printf("Invalid packet (joinroutine_known)!\n"); return length; } //Map-Hash int stringsize = message[position]; if (stringsize > 255 || stringsize >= (length-position+1)) { printf("Mapname too big\n"); return length; } position++; unsigned char *mapname = malloc(stringsize); if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(mapname, message+position, stringsize); mapname[stringsize] = '\0'; position += stringsize; paketlength += stringsize; //printf("\tMapname: %s\n", mapname); //----------- ServerData ----------- stringsize = 28 + strlen(sv_map) + strlen(sv_name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 6; position++; buffer[position] = 0; //CheckPlayerData() position++; buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_friendlyfire; position++; buffer[position] = 0; //Unknown position++; buffer[position] = mp_roundtime; position++; buffer[position] = mp_freezetime; position++; buffer[position] = mp_c4timer; position++; buffer[position] = 32; //Unknown position++; buffer[position] = 124; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 1; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = sv_maxplayers; position++; buffer[position] = sv_fow; position++; buffer[position] = mp_specmode; position++; buffer[position] = sv_gamemode; position++; buffer[position] = mp_respawndelay; position++; buffer[position] = mp_infammo; position++; buffer[position] = 3; //strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; position++; buffer[position] = onlineplayer; position++; int i; for (i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 1 && i != id) { unsigned char *encodedname; encodedname = GetEncodedString(player[i].name, strlen(player[i].name)); unsigned short *deaths = &player[i].deaths; unsigned short tempscore = player[i].deaths + 1000; unsigned short *score = &tempscore; unsigned short tempx = (player[i].x); unsigned short tempy = (player[i].y); unsigned short *x = &tempx; unsigned short *y = &tempy; float *ptemprotation = &player[i].rotation; int playersize = 25 + strlen(encodedname); buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = i; position++; buffer[position] = strlen(encodedname); position++; memcpy(buffer+position, encodedname, strlen(encodedname)); position += strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[i].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; /* buffer[position] = score[0]; //Deaths position++; buffer[position] = score[1]; //Deaths position++; */ memcpy(buffer+position, score, 2); position += 2; /* buffer[position] = deaths[0]; //Deaths position++; buffer[position] = deaths[1]; //Deaths position++; */ memcpy(buffer+position, deaths, 2); position += 2; memcpy(buffer+position, x, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; memcpy(buffer+position, y, 2); position += 2; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = ptemprotation[0]; //Rotation position++; buffer[position] = ptemprotation[1]; //Rotation position++; buffer[position] = player[i].health; //Health position++; buffer[position] = player[i].armor; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe position++; buffer[position] = 0; //Unknown position++; /* 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 e8 03 00 00 12 01 00 00 01 03 e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 */ } } if(1) { unsigned char *encodedname; encodedname = GetEncodedString(player[id].name, strlen(player[id].name)); int playersize = 25 + strlen(encodedname); buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); buffer[position] = id; position++; buffer[position] = strlen(encodedname); position++; memcpy(buffer+position, encodedname, strlen(encodedname)); position += strlen(encodedname); free(encodedname); buffer[position] = 0; //Unknown position++; buffer[position] = player[id].team; position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 232; //Unknown position++; buffer[position] = 3; //Unknown position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //Deaths position++; buffer[position] = 0; //X position++; buffer[position] = 0; //X position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Y position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Health position++; buffer[position] = 0; //Armor position++; buffer[position] = 0; //Unknown position++; buffer[position] = 0; //Aktuelle Waffe 50 = Knife position++; buffer[position] = 0; //Unknown position++; } SendToPlayer(buffer, position, id, 1, writesocket); free(buffer); //----------- PlayerData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 1; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- HostageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 2; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ItemData ----------- /* fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 */ stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 3; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- EnityData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 4; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 5; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- ProjectileData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 6; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- DynamicObjectImageData ----------- stringsize = 4; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 7; //third payload position++; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); //----------- Final ACK ----------- stringsize = 7; buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); position = 0; buffer[position] = 252; position++; buffer[position] = 7; position++; buffer[position] = 200; //third payload position++; buffer[position] = 3; //strlen ACK position++; buffer[position] = 65; //A position++; buffer[position] = 67; //C position++; buffer[position] = 75; //K position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); player[id].joinstatus = 4; free(mapname); OnJoin(id, writesocket); } else { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } default: { printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); } break; } return paketlength; } int leave(int id, int writesocket) { OnLeave(id, writesocket); free(player[id].name); free(player[id].usgn); free(player[id].spraylogo); free(player[id].win); player[id].name = NULL; player[id].usgn = NULL; player[id].spraylogo = NULL; player[id].win = NULL; onlineplayer--; ClearPlayer(id); return 2; } + +int reload(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 2; + if(length < paketlength) + { + printf("Invalid packet (buy)!\n"); + return length; + } + + int position = 1; + int status; + + status = message[position]; + position++; + + if(status == 1) + { + SendReloadMessage(id, 1, writesocket); + player[id].reloading = player[id].actualweapon; + player[id].reloadtimer = mtime()+weapons[player[id].slot[player[id].actualweapon].id].reloadtime; + } + return paketlength; +} diff --git a/src/respond_messages.c b/src/respond_messages.c index 0b04ec9..d4b936a 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,492 +1,512 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; memcpy(buffer+position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; SendToPlayer(buffer, stringsize, id, 1, writesocket); free(buffer); SendWeaponChangeMessage(id, wpnid, writesocket); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = strlen(player[id].name); position++; memcpy(buffer+position, player[id].name, strlen(player[id].name)); position += strlen(player[id].name); buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket) { time_t actualtime; time(&actualtime); if(actualtime >= (firsttime + 5)) { firsttime = actualtime; int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } + +void SendReloadMessage(int id, int status, int writesocket) +{ + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 16; + position++; + buffer[position] = id; + position++; + buffer[position] = status; + position++; + + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); +} diff --git a/src/script-functions.c b/src/script-functions.c index 751ff61..f12ce21 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,346 +1,353 @@ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if(player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].actualweapon = i; + player[id].zoommode = 0; //CHANGE there are also silencer, ... + player[id].reloading = 0; + printf("%s switched to %s\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name); return 0; } } return 1; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK */ int OnFire(int id, int writesocket) { //printf("%s tried to shoot!\n", player[id].name); short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if(*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if(*ammo1 != -1) { *ammo1 = *ammo1-1; } } + // TODO Firetimer does not work /* int temptime = mtime(); printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); if(temptime < player[id].firetimer) { printf("Firetimer error!"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; //printf("(Debug) %d\n", player[id].firetimer); } */ int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = {0}; if(temprot < 0) { temprot = 360 - (temprot *-1); } temprot = 360 - temprot; temprot += 90; if(temprot > 360) { temprot = temprot-360; } rotx = cos((temprot)*PI/180); roty = sin((temprot)*PI/180); for(i = 1; i <= range; i++) { startx += i*rotx; starty -= i*roty; int tilex = (int)(startx)/32; int tiley = (int)(starty)/32; if(tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if(tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for(b = 1; b <= sv_maxplayers; b++) { if(player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if(sqrt( (player[b].x - startx)*(player[b].x - startx) + (player[b].y - starty)*(player[b].y - starty) ) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch(player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if(player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } int OnBuyAttempt(int id, int wpnid, int writesocket) { if(player[id].money - weapons[wpnid].price >= 0) { int i; for(i = 0; i <= 99; i++) { if(weapons[wpnid].freq != 0) //If unknown everything is 0 { return 0; } } } return 1; } int OnBuy(int id, int wpnid, int writesocket) { player[id].money -= weapons[wpnid].price; player[id].actualweapon = GivePlayerWeapon(id, wpnid); //Return slot printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); return 0; } int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; + player[hitter].score++; + player[hitter].kills++; + player[victim].deaths++; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if(team == 1) { printf("%s: %s\n", player[id].name, message); } else if(team == 2) { printf("%s (Team): %s\n", player[id].name, message); } SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if(skin != 5) { switch(team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } } if(team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } diff --git a/src/weapons.c b/src/weapons.c index a9bcb6e..c43c240 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,40 +1,45 @@ #include "../include/weapons.h" -void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2) +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2, int reloadtime) { if(name != NULL) { weapons[id].name = malloc(strlen(name)+1); if(weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); strncpy(weapons[id].name, name, strlen(name)+1); } else { weapons[id].name = NULL; } weapons[id].weapondamage = wpndmg; weapons[id].weapondamage_z1 = wpndmg_z1; weapons[id].weapondamage_z2 = wpndmg_z2; weapons[id].freq = freq; weapons[id].speed = speed; weapons[id].slot = slot; weapons[id].price = price; weapons[id].range = range; weapons[id].accuracy = accuracy; weapons[id].ammo1 = ammo1; weapons[id].ammo2 = ammo2; + weapons[id].reloadtime = reloadtime; } void WeaponInit() { int i; for(i = 0; i <= 99; i++) { - AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0); + AddWeapon(i, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0); } - AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100); - AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120); - AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 ); - AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 ); + AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100, 10000); + AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120, 10000); + AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 , 10000); + AddWeapon(4, "P228" , 22 , 0, 0, 166 , 1, 2, 600, 300, 0 , 13, 35 , 10000); + AddWeapon(5, "Elite" , 22 , 0, 0, 187 , 1, 2,1000, 300, 0 , 13, 120, 10000); + AddWeapon(6, "Five-Seven" , 21 , 0, 0, 187 , 1, 2,750 , 300, 0 , 20, 100, 10000); + AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 , 10000); + //FIXME finish reload }
Jermuk/custom_cs2dsrv
6f76e0e4afe6f32302c41f95e4b874d24b0dea61
Buy fixed (Wrong number + Missing &)
diff --git a/src/respond_messages.c b/src/respond_messages.c index 0d55cd4..1fa22b9 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,490 +1,491 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; - buffer[position] = 17; + buffer[position] = 23; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; - memcpy(buffer+position, player[id].money, 2); + memcpy(buffer+position, &player[id].money, 2); position += 2; buffer[position] = 0; position++; - //SendToAll(buffer, stringsize, 1, writesocket); + SendToAll(buffer, stringsize, 1, writesocket); free(buffer); + printf("Message sent!\n"); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = strlen(player[id].name); position++; memcpy(buffer+position, player[id].name, strlen(player[id].name)); position += strlen(player[id].name); buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket) { time_t actualtime; time(&actualtime); if(actualtime >= (firsttime + 5)) { firsttime = actualtime; int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } }
Jermuk/custom_cs2dsrv
ad0d64422afa79a6f5e3410b8ccdeb012944e533
Buy fixed (Wrong number)
diff --git a/src/main.c b/src/main.c index 881a8c6..e94c748 100644 --- a/src/main.c +++ b/src/main.c @@ -1,191 +1,191 @@ #include "../include/main.h" time_t firsttime; int main() { int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); time(&firsttime); while(1) { CheckForTimeout(); PingAllPlayer(readsocket); select(readsocket+1, &descriptor, NULL, NULL, NULL); if(FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); if(id != -1) { if (ValidatePaket(buffer, id)) { PaketConfirmation(buffer, id, readsocket); time(&player[id].lastpaket); int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; - case 17: - rtn = buy(message, tempsize, id, readsocket); - break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; + case 23: + rtn = buy(message, tempsize, id, readsocket); + break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return 0; }
Jermuk/custom_cs2dsrv
81a55db35b8f1bc193540abf5c5bf40a6096088f
Log Activated!
diff --git a/.project b/.project index eb3f880..2dad120 100644 --- a/.project +++ b/.project @@ -1,70 +1,70 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>custom_cs2dsrv</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name> <triggers>clean,full,incremental,</triggers> <arguments> <dictionary> <key>?name?</key> <value></value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.append_environment</key> <value>true</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.buildArguments</key> <value></value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.buildCommand</key> <value>make</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.buildLocation</key> - <value>${workspace_loc:/custom_cs2dsrv/Debug}</value> + <value>${workspace_loc:/custom_cs2dsrv/Release}</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.contents</key> <value>org.eclipse.cdt.make.core.activeConfigSettings</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.enableAutoBuild</key> <value>false</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.enableCleanBuild</key> <value>true</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.enableFullBuild</key> <value>true</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.stopOnError</key> <value>true</value> </dictionary> <dictionary> <key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key> <value>true</value> </dictionary> </arguments> </buildCommand> <buildCommand> <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name> <triggers>full,incremental,</triggers> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.cdt.core.cnature</nature> <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature> <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature> </natures> </projectDescription> diff --git a/log.txt b/log.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/log.c b/src/log.c index 58bb859..9a90a6a 100644 --- a/src/log.c +++ b/src/log.c @@ -1,49 +1,49 @@ #include "../include/log.h" void myprintf(char *string, ...) { FILE *logfile; time_t rawtime; struct tm * timeinfo; logfile = fopen("log.txt","a+"); if(logfile != NULL) { time(&rawtime); timeinfo = localtime(&rawtime); - //fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); - //vfprintf(logfile, string, argzeiger); + vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } } void myprintf2(char *string, ...) { FILE *logfile; logfile = fopen("log.txt","a+"); if(logfile != NULL) { va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); - //vfprintf(logfile, string, argzeiger); + vfprintf(logfile, string, argzeiger); va_end(argzeiger); fclose(logfile); } else { printf("Cannot open logfile!\n"); } }
Jermuk/custom_cs2dsrv
b648615fc6388ccf5bae87eba1ccae27fa2a234f
Added Buy Support
diff --git a/include/functions.h b/include/functions.h index 0ed1900..dde10f8 100644 --- a/include/functions.h +++ b/include/functions.h @@ -1,23 +1,23 @@ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include "main.h" int IsPlayerKnown(struct in_addr ip, u_short port); void ClearPlayer(int id); void ClearAllPlayer(void); void CheckForTimeout(void); -void GivePlayerWeapon(int id, int wpnid); +int GivePlayerWeapon(int id, int wpnid); void RemovePlayerWeapon(int id, int wpnid); void RemoveAllPlayerWeapon(int id); int PlayerTimeout(int id); unsigned short GetServerStatus(void); unsigned short endian_swap_short(unsigned short *x); unsigned int endian_swap_int(unsigned int *x); int ValidatePaket(char *message, int id); void PaketConfirmation(char *message, int id, int writesocket); int CheckPlayerData(char *password); unsigned char *GetEncodedString(unsigned char *string, int length); extern time_t firsttime; #endif // FUNCTIONS_H_INCLUDED diff --git a/include/script-functions.h b/include/script-functions.h index d118787..06622d9 100644 --- a/include/script-functions.h +++ b/include/script-functions.h @@ -1,22 +1,22 @@ #ifndef SCRIPT_H_INCLUDED #define SCRIPT_H_INCLUDED #include "main.h" int OnJoin(int id, int writesocket); int OnLeave(int id, int writesocket); int OnSpecmove(int id, int newx, int newy, int writesocket); int OnServerStart(); int OnExit(); int OnRespawnRequest(int id, int writesocket); int OnRespawn(int id, int writesocket); int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); int OnFire(int id, int writesocket); int OnHit(int hitter, int victim, int writesocket); -int OnBuy(int id, int wpnid, int writesocket); +int OnBuyAttempt(int id, int wpnid, int writesocket); int OnKill(int hitter, int victim, int wpnid, int writesocket); int OnChatMessage(int id, unsigned char *message, int team, int writesocket); int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket); int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket); int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket); #endif diff --git a/include/structs.h b/include/structs.h index a373fe6..71cd4be 100644 --- a/include/structs.h +++ b/include/structs.h @@ -1,74 +1,73 @@ #ifndef STRUCTS_H_INCLUDED #define STRUCTS_H_INCLUDED #include "main.h" struct WEAPON { short weapondamage, weapondamage_z1, weapondamage_z2; short shoottime, reloadtime; float freq; short speed; short slot; short price; short range; short accuracy; short ammo1, ammo2; char *name; }; -struct WEAPON weapons[100]; struct PLAYER_WEAPON { short id, slot; short ammo1, ammo2; }; struct PLAYER { int used; unsigned short client_nummer; unsigned short server_nummer; time_t lastpaket; unsigned short joinstatus; unsigned char *name; unsigned char *spraylogo; unsigned char *win; unsigned short version; unsigned short *usgn; unsigned char team; unsigned char skin; short deaths, score; unsigned short x,y; unsigned char health, armor; unsigned char actualweapon; struct PLAYER_WEAPON slot[10]; float rotation; //-180 to +180 int specposx, specposy; unsigned short money; short dead; int start; int latency; int firetimer; int zoommode; /* Address*/ unsigned short port; struct in_addr ip; }; struct PLAYER player[MAX_CLIENTS]; struct TILE { unsigned char mode; unsigned char tileid; }; struct TILE **map; #endif // STRUCTS_H_INCLUDED diff --git a/include/weapons.h b/include/weapons.h index fb2564f..dc3e39c 100644 --- a/include/weapons.h +++ b/include/weapons.h @@ -1,8 +1,10 @@ #ifndef WEAPONS_H_INCLUDED #define WEAPONS_H_INCLUDED #include "main.h" void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2); void WeaponInit(); +struct WEAPON weapons[100]; + #endif // WEAPONS_H_INCLUDED diff --git a/log.txt b/log.txt deleted file mode 100644 index e69de29..0000000 diff --git a/src/functions.c b/src/functions.c index 2c6431a..268bcee 100644 --- a/src/functions.c +++ b/src/functions.c @@ -1,307 +1,307 @@ #include "../include/functions.h" int IsPlayerKnown(struct in_addr ip, u_short port) { int i; for (i = 1; i <= sv_maxplayers; i++) { if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) { return i; } } return -1; } void ClearPlayer(int id) { player[id].used = 0; player[id].client_nummer = 0; player[id].server_nummer = 0; player[id].lastpaket = 0; player[id].joinstatus = 0; free(player[id].name); player[id].name = NULL; free(player[id].spraylogo); player[id].spraylogo = NULL; free(player[id].win); player[id].win = NULL; free(player[id].usgn); player[id].usgn = NULL; player[id].version = 0; player[id].team = 0; player[id].deaths = 0; player[id].score = 0; player[id].x = 0; player[id].y = 0; player[id].health = 0; player[id].armor = 0; player[id].actualweapon = 0; int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; } player[id].rotation = 0; player[id].dead = 1; player[id].start = 0; player[id].money = mp_startmoney; player[id].zoommode = 0; /* Address*/ player[id].port = 0; //player[id].ip = ""; } void ClearAllPlayer(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { ClearPlayer(i); } } void CheckForTimeout(void) { int i; for (i = 1; i <= sv_maxplayers; i++) { if (PlayerTimeout(i)) { printf("Client %d timed out!\n", i); ClearPlayer(i); } } } -void GivePlayerWeapon(int id, int wpnid) +int GivePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == 0) { player[id].slot[i].id = wpnid; player[id].slot[i].slot = weapons[wpnid].slot; player[id].slot[i].ammo1 = weapons[wpnid].ammo1; player[id].slot[i].ammo2 = weapons[wpnid].ammo2; - break; + return i; } } } void RemovePlayerWeapon(int id, int wpnid) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; break; } } } void RemoveAllPlayerWeapon(int id) { int i; for(i = 0; i <= 9; i++) { player[id].slot[i].id = 0; player[id].slot[i].slot = 0; player[id].slot[i].ammo1 = 0; player[id].slot[i].ammo2 = 0; } } int PlayerTimeout(int id) { id = 0; /* time_t actualtime; time(&actualtime); if(((player[id].lastpaket + TIMEOUT) > actualtime) && player[id].lastpaket != 0) { printf("POSITIV!\n"); return 1; } */ return 0; } unsigned short GetServerStatus(void) // { unsigned short serverstatus = 0; if(strcmp(sv_password, "")) { serverstatus += 1; } if(sv_usgnonly == 1) { serverstatus += 2; } if(sv_fow == 1) { serverstatus += 4; } if(sv_friendlyfire == 1) { serverstatus += 8; } if(1) //Same Version? { serverstatus += 16; } if(sv_gamemode != 0) { serverstatus += 32; } if(0) //LuaScripts { serverstatus += 64; } if(1) //Dedicated { serverstatus += 128; } return serverstatus; } unsigned short endian_swap_short(unsigned short *x) { *x = (*x>>8) | (*x<<8); return *x; } unsigned int endian_swap_int(unsigned int *x) { *x = (*x>>24) | ((*x<<8) & 0x00FF0000) | ((*x>>8) & 0x0000FF00) | (*x<<24); return *x; } int ValidatePaket(char *message, int id) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 != 0) { if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) { printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); free(pTempNummer); return 0; } } if(*pTempNummer-1 > player[id].client_nummer) { player[id].client_nummer = *pTempNummer; } /* unsigned short *pNummer = &player[id].client_nummer; pNummer[0] = buffer[0]; pNummer[1] = buffer[1]; */ free(pTempNummer); return 1; } void PaketConfirmation(char *message, int id, int writesocket) { unsigned short *pTempNummer = malloc(sizeof(unsigned short)); pTempNummer[0] = message[0]; pTempNummer[1] = message[1]; if(*pTempNummer % 2 == 0) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); buffer[0] = 0x01; memcpy(buffer+1, pTempNummer, 2); SendToPlayer(buffer, stringsize, id, 0, writesocket); free(buffer); } free(pTempNummer); } int CheckPlayerData(char *password) { if(strcmp(sv_password, password) != 0) { printf("Password wrong!\n"); return 1; } if(sv_maxplayers == onlineplayer) { printf("Server full!\n"); return 3; } /* 0 - Normal 1 - Password wrong 2 - USGN only 3 - Server full 4 - Banned 5 - Another Game Version 6 - ?? 7 - Can't validate user (USGN offline) 8 - ?? 9 - Connection already exists 10 - Wrong client (pre_authcode) 11 - Diffrent map (temp, etc.) 12 - Map unknown (maptransfer disabled) 13++ - Failed to join */ return 0; } unsigned char *GetEncodedString(unsigned char *string, int length) { unsigned char *buffer = malloc(length+1); //+1 need for \0 if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); int i; for (i = 0; i <= length; i++) { if ((i % 3) == 0) { buffer[i] = string[i] + 110; } else if ((i % 3) == 1) { buffer[i] = string[i] + 97; } else if ((i % 3) == 2) { buffer[i] = string[i] + 109; } } buffer[length] = '\0'; return buffer; } diff --git a/src/main.c b/src/main.c index 6785da2..881a8c6 100644 --- a/src/main.c +++ b/src/main.c @@ -1,188 +1,191 @@ #include "../include/main.h" time_t firsttime; int main() { int readsocket; struct sockaddr_in newclient; unsigned char buffer[MAX_BUF]; int size; fd_set descriptor; //I don't know ClearAllPlayer(); WeaponInit(); readsocket = create_socket(); bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); atexit(cleanup); FD_ZERO(&descriptor); FD_SET(readsocket, &descriptor); OnServerStart(); ReadMap(); time(&firsttime); while(1) { CheckForTimeout(); PingAllPlayer(readsocket); select(readsocket+1, &descriptor, NULL, NULL, NULL); if(FD_ISSET(readsocket, &descriptor)) { size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); if (size < 3) { printf("Invalid paket! (size < 3)\n"); } else { int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); if(id != -1) { if (ValidatePaket(buffer, id)) { PaketConfirmation(buffer, id, readsocket); time(&player[id].lastpaket); int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_known(message, tempsize, id, readsocket); break; case 3: rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); break; case 7: rtn = fire(message, tempsize, id, readsocket); break; case 9: rtn = weaponchange(message, tempsize, id, readsocket); break; case 10: rtn = posupdaterun(message, tempsize, id, readsocket); break; case 11: rtn = posupdatewalk(message, tempsize, id, readsocket); break; case 12: rtn = rotupdate(message, tempsize, id, readsocket); break; case 13: rtn = posrotupdaterun(message, tempsize, id, readsocket); break; case 14: rtn = posrotupdatewalk(message, tempsize, id, readsocket); break; + case 17: + rtn = buy(message, tempsize, id, readsocket); + break; case 20: rtn = teamchange(message, tempsize, id, readsocket); break; case 32: rtn = specpos(message, tempsize, id, readsocket); break; case 39: rtn = respawnrequest(message, tempsize, id, readsocket); break; case 240: rtn = chatmessage(message, tempsize, id, readsocket); break; case 249: rtn = ping_ingame(message, tempsize, id, readsocket); break; case 252: rtn = joinroutine_known(message, tempsize, id, readsocket); break; case 253: rtn = leave(id, readsocket); break; default: SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } else { int control = 1; int position = 2; while(control) { int tempsize = size - position; unsigned char *message = malloc(tempsize); memcpy(message, buffer+position, tempsize); int rtn = 0; switch(message[0]) //payload { case 1: rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 3: rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); break; case 250: rtn = ping_serverlist(message, tempsize, &newclient, readsocket); break; case 251: rtn = serverinfo_request(message, tempsize, &newclient, readsocket); break; case 252: rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); break; default: unknown(message, tempsize, buffer, size, position); rtn = tempsize; break; } position = position + rtn; if (position == size) { free(message); break; } else if (position > size) { printf("Error while reading packet: position(%d) > size(%d)\n", position, size); free(message); } free(message); } } } } } return 0; } diff --git a/src/pakets.c b/src/pakets.c index 4b4e862..8c5fa1b 100644 --- a/src/pakets.c +++ b/src/pakets.c @@ -1,628 +1,629 @@ #include "../include/pakets.h" int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) { int paketlength = length; int i; printf("Unknown packet: "); for(i = 2; i <= position-1; i++) { eprintf("%d-", buffer[i]); } eprintf("\n\t"); for(i = 0; i <= length; i++) { eprintf("%d-", message[i]); } eprintf("\n"); return paketlength; } int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_unknown)!\n"); return length; } return paketlength; } int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (connection_setup_known)!\n"); return length; } return paketlength; } int ping_ingame(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_ingame)!\n"); return length; } player[id].latency = mtime() - player[id].start; return paketlength; } int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_unknown)!\n"); return length; } return paketlength; } int confirmation_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (confirmation_known)!\n"); return length; } return paketlength; } int fire(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (fire)!\n"); return length; } switch(OnFire(id, writesocket)) { case 0: SendFireMessage(id, writesocket); break; case 1: break; } return paketlength; } int buy(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (buy)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; - switch(OnBuy(id, wpnid, writesocket)) + switch(OnBuyAttempt(id, wpnid, writesocket)) { case 0: + OnBuy(id, wpnid, writesocket); SendBuyMessage(id, wpnid, writesocket); break; case 1: break; } return paketlength; } int rotupdate(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; float temprotation; if(length < paketlength) { printf("Invalid packet (rot_update)!\n"); return length; } memcpy(&temprotation, message+1, sizeof(float)); if(temprotation >= -180 && temprotation <= 180) { //if(temprotation < 0) temprotation += 360; memcpy(&player[id].rotation, &temprotation, sizeof(float)); SendRotUpdate(id, player[id].rotation, writesocket); } return paketlength; } int posupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 0, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); break; default: break; } return paketlength; } int posupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 5; unsigned short tempx; unsigned short tempy; if(length < paketlength) { printf("Invalid packet (posupdaterun)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: SendPosUpdate(id, tempx, tempy, 1, writesocket); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); break; default: break; } return paketlength; } int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; unsigned short tempx; unsigned short tempy; float rotation; if(length < paketlength) { printf("Invalid packet (posrotupdatewalk)!\n"); return length; } memcpy(&tempx, message+1, 2); memcpy(&tempy, message+3, 2); memcpy(&rotation, message+5, sizeof(float)); if(rotation >= -180 && rotation <= 180) { switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) { case 0: //if(rotation < 0) rotation += 360; SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); memcpy(&player[id].rotation, &rotation, sizeof(float)); player[id].x = tempx; player[id].y = tempy; break; case 1: SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); break; default: break; } } return paketlength; } int respawnrequest(unsigned char *message, int length, int id, int writesocket) { int paketlength = 1; if(length < paketlength) { printf("Invalid packet (respawnrequest)! (WTF?)\n"); return length; } switch(OnRespawnRequest(id, writesocket)) { case 0: srand(time(NULL)); switch(player[id].team) { case 0: printf("%s tried to spawn as spectator!\n", player[id].name); break; case 1: { int tmp = rand() % tspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (tspawnx[tmp]+0.5)*32; player[id].y = (tspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } case 2: { int tmp = rand() % ctspawncount; printf("%s spawned!\n", player[id].name); player[id].health = 100; player[id].dead = 0; player[id].x = (ctspawnx[tmp]+0.5)*32; player[id].y = (ctspawny[tmp]+0.5)*32; SendSpawnMessage(id, player[id].x, player[id].y, writesocket); break; } } break; case 1: break; default: break; } return paketlength; } int weaponchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (weaponchange)!\n"); return length; } int position = 1; int wpnid; wpnid = message[position]; position++; switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) { case 0: SendWeaponChangeMessage(id, wpnid, writesocket); break; case 1: break; default: break; } return paketlength; } int teamchange(unsigned char *message, int length, int id, int writesocket) { int paketlength = 3; if(length < paketlength) { printf("Invalid packet (teamchange)!\n"); return length; } unsigned char team = message[1]; unsigned char skin = message[2]; switch(OnTeamChangeAttempt(id, team, skin, writesocket)) { case 0: player[id].team = team; if(skin != 5) player[id].skin = skin; OnTeamChange(id, team, skin, writesocket); break; case 1: break; default: break; } return paketlength; } int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = 5; if(length < paketlength) { printf("Invalid packet (ping_serverlist)!\n"); return length; } unsigned char *tempbuffer = malloc(paketlength); if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); tempbuffer[0] = 0x01; tempbuffer[1] = 0x00; memcpy(tempbuffer+2, message, paketlength); udp_send(writesocket, tempbuffer, 5, client); free(tempbuffer); return paketlength; } int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; if(length < 2) { printf("Invalid packet (serverinfo_request)!\n"); return length; } /* int i; printf("serverinfo_request (%d): ", message[0]); for (i = 1; i <= paketlength; i++) { printf("%d-", message[i]); } printf("(%d)\n", paketlength); int joinroutine_known(unsigned char *message, int length, int id, int writesocket) */ int stringsize = 10 + strlen(sv_name) + strlen(sv_map); if(sv_gamemode != 0) { stringsize++; } unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); int position = 0; buffer[position] = 1; position++; buffer[position] = 0; position++; buffer[position] = 0xFB; position++; buffer[position] = message[1]; position++; switch(message[1]) { case 1: case 2: /* if(message[2] == 0) { paketlength = 2; } else { paketlength = 6; } */ paketlength = 4; buffer[position] = GetServerStatus(); position++; buffer[position] = strlen(sv_name); position++; memcpy(buffer+position, sv_name, strlen(sv_name)); position += strlen(sv_name); buffer[position] = strlen(sv_map); position++; memcpy(buffer+position, sv_map, strlen(sv_map)); position += strlen(sv_map); buffer[position] = onlineplayer; position++; buffer[position] = sv_maxplayers; position++; if(sv_gamemode != 0) { buffer[position] = sv_gamemode; position++; } buffer[position] = bot_count; position++; udp_send(writesocket, buffer, stringsize, client); break; case 4: break; case 5: break; default: break; } free(buffer); return paketlength; } int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) { int paketlength = length; //Just 2 char read (message[1]) if(length < 2) { printf("Invalid packet (joinroutine_unknown)!\n"); return length; } switch(message[1]) { case 0x00: { paketlength = 2; int i; for (i = 1; i <= MAX_CLIENTS; i++) { if (player[i].used != 1) { player[i].used = 1; player[i].ip = client->sin_addr; player[i].port = client->sin_port; player[i].joinstatus = 1; player[i].client_nummer = 4; player[i].server_nummer = 2; break; } } int stringsize = 5 + strlen(pre_authcode); unsigned char *buffer = malloc(stringsize); if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); int position = 0; buffer[position] = 0x01; position++; buffer[position] = 0x00; position++; buffer[position] = 0xFC; position++; buffer[position] = 0x00; position++; buffer[position] = strlen(pre_authcode); position++; memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); udp_send(writesocket, buffer, stringsize, client); free(buffer); break; } default: printf("Unexpected join data (%d)\n", message[0]); break; } return paketlength; } int specpos(unsigned char *message, int length, int id, int writesocket) { int paketlength = 9; if(paketlength > length) { printf("Invalid packet (specpos)!\n"); return length; } int x, y; x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; switch(OnSpecmove(id, x, y, writesocket)) { case 0: { player[id].specposx = x; player[id].specposy = y; break; } case 1: { break; } } return paketlength; } int chatmessage(unsigned char *message, int length, int id, int writesocket) { int paketlength=4; unsigned char team, unknown; int paketsize; if(paketlength > length) { printf("Invalid packet (chatmessage)!\n"); return length; } int position = 0; position++; team = message[position]; position++; paketsize = message[position]; if (paketsize > 255 || paketsize >= (length-position+1)) { printf("Message too big\n"); return length; } position++; paketlength += paketsize; unknown = message[position]; position++; unsigned char *string = malloc(paketsize); if (string == NULL) error_exit("Memory error ( joinroutine_known() )\n"); memcpy(string, message+position, paketsize); string[paketsize] = '\0'; position += paketsize; switch(OnChatMessage(id, string, team, writesocket)) { case 0: break; default: printf("Unknown Return value for OnChatMessage()!\n"); break; } free(string); return paketlength; } int joinroutine_known(unsigned char *message, int length, int id, int writesocket) { int paketlength = 2; if(paketlength > length) { diff --git a/src/respond_messages.c b/src/respond_messages.c index e4271e7..0d55cd4 100644 --- a/src/respond_messages.c +++ b/src/respond_messages.c @@ -1,484 +1,490 @@ #include "../include/respond_messages.h" void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) { int stringsize = 11; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *spawnx = &x; unsigned short *spawny = &y; unsigned short *pmoney = &player[id].money; buffer[position] = 21; position++; buffer[position] = id; position++; memcpy(buffer+position, spawnx, 2); position += 2; memcpy(buffer+position, spawny, 2); position += 2; buffer[position] = 50; //Team position++; buffer[position] = 0; position++; /* buffer[position] = pmoney[1]; //Money position++; buffer[position] = pmoney[0]; // Money position++; */ memcpy(buffer+position, pmoney, 2); position += 2; int i, count; count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); buffer[position] = count; position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= count-1; i++) { buffer[position] = startweapons[i]; position++; GivePlayerWeapon(id, startweapons[i]); if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 } /* int count, i; count = 0; for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { count++; } } buffer[position] = count; //Count position++; buffer = realloc(buffer, stringsize + count); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); for(i = 0; i <= 10; i++) { if(player[id].slot[i].id != 0) { buffer[position] = player[id].slot[i].id; position++; } } */ SendToAll(buffer, stringsize + count, 1, writesocket); free(buffer); } void SendFireMessage(int id, int writesocket) { int stringsize = 2; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); int position = 0; buffer[position] = 7; position++; buffer[position] = id; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendBuyMessage(int id, int wpnid, int writesocket) { - int stringsize = 2; + int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); int position = 0; - buffer[position] = 7; + buffer[position] = 17; position++; buffer[position] = id; position++; + buffer[position] = wpnid; + position++; + memcpy(buffer+position, player[id].money, 2); + position += 2; + buffer[position] = 0; + position++; //SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendHitMessage(int id, int victim, int health, int writesocket) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); int position = 0; buffer[position] = 17; position++; buffer[position] = id; position++; buffer[position] = victim; position++; buffer[position] = health; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendWeaponChangeMessage(int id, int wpnid, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); int position = 0; buffer[position] = 9; position++; buffer[position] = id; position++; buffer[position] = wpnid; position++; buffer[position] = 0; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; if(status == 0) buffer[position] = 11; else if(status == 1) buffer[position] = 10; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) { int stringsize = 10; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); int position = 0; unsigned short *px = &x; unsigned short *py = &y; //if(rotation > 180) rotation = (rotation - 360); //unsigned short *protation = &rotation; //2 Bytes cut off if(status == 0) buffer[position] = 14; else if(status == 1) buffer[position] = 13; position++; buffer[position] = id; position++; memcpy(buffer+position, px, 2); position += 2; memcpy(buffer+position, py, 2); position += 2; memcpy(buffer+position, &rotation, 4); position += 4; SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendRotUpdate(int id, float rotation, int writesocket) { int stringsize = 6; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); int position = 0; //if(rotation > 180) rotation = (rotation - 360); buffer[position] = 12; position++; buffer[position] = id; position++; memcpy(buffer+position, &rotation, sizeof(float)); SendToAllOther(id, buffer, stringsize, 1, writesocket); free(buffer); } void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToPlayer(buffer, stringsize, id, 1, writesocket); switch(status) { case 1: printf("To %s (Chat): %s\n", player[id].name ,message); break; case 2: printf("To %s (Screen): %s\n", player[id].name ,message); break; case 3: printf("To %s (Console): %s\n", player[id].name ,message); break; default: printf("Unknown status (SendMessageToPlayer())!\n"); break; } free(buffer); } void SendMessageToAll(unsigned char *message, int status, int writesocket) { /* 1 - Chat 2 - Screen 3 - Console 4 - Crash */ int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = 0; position++; buffer[position] = status; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); SendToAll(buffer, stringsize, 1, writesocket); switch(status) { case 1: printf("To All (Chat): %s\n", message); break; case 2: printf("To All (Screen): %s\n", message); break; case 3: printf("To All (Console): %s\n", message); break; default: printf("Unknown status (SendMessageToAll())!\n"); break; } free(buffer); } void SendJoinMessage(int id, int writesocket) { int stringsize = 4 + strlen(player[id].name); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 248; position++; buffer[position] = id; position++; buffer[position] = strlen(player[id].name); position++; memcpy(buffer+position, player[id].name, strlen(player[id].name)); position += strlen(player[id].name); buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void SendLeaveMessage(int id, int writesocket) { if(player[id].joinstatus >= 4) { int stringsize = 3; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); int position = 0; buffer[position] = 253; position++; buffer[position] = id; position++; buffer[position] = 0; //strlen ACK position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } } void SendChatMessage(int id, unsigned char *message, int team, int writesocket) { int stringsize = 5 + strlen(message); unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); int position = 0; buffer[position] = 240; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = strlen(message); position++; buffer[position] = 0; position++; memcpy(buffer+position, message, strlen(message)); position += strlen(message); if(team == 1) { SendToAll(buffer, stringsize, 1, writesocket); } else if(team == 2) { SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); } free(buffer); } void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) { int stringsize = 4; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 20; position++; buffer[position] = id; position++; buffer[position] = team; position++; buffer[position] = skin; position++; SendToAll(buffer, stringsize, 1, writesocket); free(buffer); } void PingAllPlayer(int writesocket) { time_t actualtime; time(&actualtime); if(actualtime >= (firsttime + 5)) { firsttime = actualtime; int i; for(i = 1; i <= sv_maxplayers; i++) { if(player[i].used == 1 && player[i].joinstatus >= 4) { int stringsize = 5; unsigned char *buffer = malloc(stringsize); if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); int position = 0; buffer[position] = 249; position++; buffer[position] = 0; position++; buffer[position] = 32; position++; buffer[position] = 191; position++; buffer[position] = 0; position++; player[i].start = mtime(); SendToPlayer(buffer, stringsize, i, 0, writesocket); free(buffer); } } } } diff --git a/src/script-functions.c b/src/script-functions.c index a64803c..8cf8d92 100644 --- a/src/script-functions.c +++ b/src/script-functions.c @@ -1,331 +1,345 @@ #include "../include/script-functions.h" /* int OnJoin(int id, int writesocket) id - Who joins Return Values: 0 - OK */ int OnJoin(int id, int writesocket) { SendJoinMessage(id, writesocket); printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); return 0; } /* int OnLeave(int id, int writesocket) id - Who leaves Return Values: 0 - OK */ int OnLeave(int id, int writesocket) { SendLeaveMessage(id, writesocket); printf("%s has left the game!\n", player[id].name); return 0; } /* int OnSpecmove(int id, int newx, int newy, int writesocket) Return Values: 0 - OK 1 - Don't save it */ int OnSpecmove(int id, int newx, int newy, int writesocket) { return 0; } /* int OnServerstart() Return Values: 0 - OK */ int OnServerStart() { time_t rawtime; time(&rawtime); printf("********** Server started **********\n"); printf("%s", ctime(&rawtime)); return 0; } /* int OnExit() Return Values: 0 - OK */ int OnExit() { printf("********** Server Shutdown! **********\n\n\n\n\n"); return 0; } /* int OnRespawnRequest(int id, int writesocket) Return Values: 0 - Respawn 1 - Don't Respawn */ int OnRespawnRequest(int id, int writesocket) { if(player[id].dead == 1) return 0; else return 1; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnRespawn(int id, int writesocket) { return 0; } /* int OnRespawn(int id, int writesocket) Return Values: 0 - OK */ int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) { int i; for(i = 0; i <= 9; i++) { if(player[id].slot[i].id == wpnid) { player[id].actualweapon = i; printf("%s switched to %s (%d)\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name, player[id].slot[player[id].actualweapon].ammo1); return 0; } } return 1; } /* int OnFire(int id, int writesocket) Return Values: 0 - OK */ int OnFire(int id, int writesocket) { short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; if(*ammo1 <= 0 && *ammo1 != -1) { printf("Not enough ammo!\n"); return 1; } else { if(*ammo1 != -1) { *ammo1 = *ammo1-1; } } /* int temptime = mtime(); printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); if(temptime < player[id].firetimer) { printf("Firetimer error!"); return 1; } else { player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; //printf("(Debug) %d\n", player[id].firetimer); } */ int i; int range = weapons[player[id].slot[player[id].actualweapon].id].range; int startx = player[id].x; int starty = player[id].y; float rotx; float roty; float temprot = player[id].rotation; short playershit[MAX_CLIENTS] = {0}; if(temprot < 0) { temprot = 360 - (temprot *-1); } temprot = 360 - temprot; temprot += 90; if(temprot > 360) { temprot = temprot-360; } rotx = cos((temprot)*PI/180); roty = sin((temprot)*PI/180); for(i = 1; i <= range; i++) { startx += i*rotx; starty -= i*roty; int tilex = (int)(startx)/32; int tiley = (int)(starty)/32; if(tilex <= 0 || tiley <= 0) break; int tilemode = map[tilex][tiley].mode; if(tilemode == 1 || tilemode == 3 || tilemode == 4) { break; } int b; for(b = 1; b <= sv_maxplayers; b++) { if(player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) { if(sqrt( (player[b].x - startx)*(player[b].x - startx) + (player[b].y - starty)*(player[b].y - starty) ) <= 16) { OnHit(id, b, writesocket); playershit[b] = 1; } } } } return 0; } /* int OnHit(int hitter, int victim, int writesocket) Return Values: 0 - OK */ int OnHit(int hitter, int victim, int writesocket) { int wpnid = player[hitter].slot[player[hitter].actualweapon].id; int damage; switch(player[hitter].zoommode) { case 0: damage = weapons[wpnid].weapondamage; break; case 1: damage = weapons[wpnid].weapondamage_z1; break; case 2: damage = weapons[wpnid].weapondamage_z2; break; default: damage = weapons[wpnid].weapondamage; break; } if(player[victim].health - damage > 0) { player[victim].health -= damage; SendHitMessage(victim, hitter, player[victim].health, writesocket); //printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); } else { OnKill(hitter, victim, wpnid, writesocket); } return 0; } -int OnBuy(int id, int wpnid, int writesocket) +int OnBuyAttempt(int id, int wpnid, int writesocket) { if(player[id].money - weapons[wpnid].price >= 0) { - player[id].money -= weapons[wpnid].price; - return 0; + int i; + for(i = 0; i <= 99; i++) + { + if(weapons[wpnid].freq != 0) //If unknown everything is 0 + { + return 0; + } + } } return 1; } +int OnBuy(int id, int wpnid, int writesocket) +{ + player[id].money -= weapons[wpnid].price; + player[id].actualweapon = GivePlayerWeapon(id, wpnid); + printf("%s bought %s!\n", player[id].name, weapons[wpnid].name); + return 0; +} + int OnKill(int hitter, int victim, int wpnid, int writesocket) { player[victim].health = 0; player[victim].dead = 1; RemoveAllPlayerWeapon(victim); SendHitMessage(victim, hitter, player[victim].health, writesocket); printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); return 0; } /* int OnChatMessage(int id, unsigned char *message, int team, int writesocket) Return Values: 0 - OK */ int OnChatMessage(int id, unsigned char *message, int team, int writesocket) { if(team == 1) { printf("%s: %s\n", player[id].name, message); } else if(team == 2) { printf("%s (Team): %s\n", player[id].name, message); } SendChatMessage(id, message, team, writesocket); return 0; } /* int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK 1 - Don't join */ int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) { return 0; } /* int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) Return Values: 0 - OK */ int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) { if(skin != 5) { switch(team) { case 0: printf("%s is now spectator\n", player[id].name); break; case 1: printf("%s is now terrorist\n", player[id].name); break; case 2: printf("%s is now counter-terrorist\n", player[id].name); break; default: printf("%s joined a unknown team\n", player[id].name); break; } } if(team <= 2) { SendTeamChangeMessage(id, team, skin, writesocket); } return 0; } /* int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) Return Values: 0 - OK 1 - Don't move */ int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) { /* int newx = (int)ceil((x)/32); int newy = (int)ceil((y)/32); printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); */ return 0; } diff --git a/src/weapons.c b/src/weapons.c index 00fca6a..10b2381 100644 --- a/src/weapons.c +++ b/src/weapons.c @@ -1,28 +1,33 @@ #include "../include/weapons.h" void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2) { weapons[id].name = malloc(strlen(name)+1); if(weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); strncpy(weapons[id].name, name, strlen(name)+1); weapons[id].weapondamage = wpndmg; weapons[id].weapondamage_z1 = wpndmg_z1; weapons[id].weapondamage_z2 = wpndmg_z2; weapons[id].freq = freq; weapons[id].speed = speed; weapons[id].slot = slot; weapons[id].price = price; weapons[id].range = range; weapons[id].accuracy = accuracy; weapons[id].ammo1 = ammo1; weapons[id].ammo2 = ammo2; } void WeaponInit() { + int i; + for(i = 0; i <= 99; i++) + { + AddWeapon(i, "Unknown", 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0); + } AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100); AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120); AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 ); AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 ); }
Jermuk/custom_cs2dsrv
6255204ef9a25fe8f1199d2f4c34f315aeaf725a
First try with git!
diff --git a/.cproject b/.cproject new file mode 100644 index 0000000..580450d --- /dev/null +++ b/.cproject @@ -0,0 +1,604 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?fileVersion 4.0.0?> + +<cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage"> + <storageModule moduleId="org.eclipse.cdt.core.settings"> + <cconfiguration id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458"> + <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458" moduleId="org.eclipse.cdt.core.settings" name="Debug"> + <externalSettings/> + <extensions> + <extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/> + <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + </extensions> + </storageModule> + <storageModule moduleId="cdtBuildSystem" version="4.0.0"> + <configuration artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.exe" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.exe" cleanCommand="rm -rf" description="" id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458" name="Debug" parent="cdt.managedbuild.config.gnu.mingw.exe.debug"> + <folderInfo id="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458." name="/" resourcePath=""> + <toolChain id="cdt.managedbuild.toolchain.gnu.mingw.exe.debug.1188392895" name="MinGW GCC" superClass="cdt.managedbuild.toolchain.gnu.mingw.exe.debug"> + <targetPlatform id="cdt.managedbuild.target.gnu.platform.mingw.exe.debug.433122987" name="Debug Platform" superClass="cdt.managedbuild.target.gnu.platform.mingw.exe.debug"/> + <builder buildPath="${workspace_loc:/custom_cs2dsrv/Debug}" id="cdt.managedbuild.tool.gnu.builder.mingw.base.442254957" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="CDT Internal Builder" superClass="cdt.managedbuild.tool.gnu.builder.mingw.base"/> + <tool id="cdt.managedbuild.tool.gnu.assembler.mingw.exe.debug.172730339" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.mingw.exe.debug"> + <inputType id="cdt.managedbuild.tool.gnu.assembler.input.671771288" superClass="cdt.managedbuild.tool.gnu.assembler.input"/> + </tool> + <tool id="cdt.managedbuild.tool.gnu.archiver.mingw.base.452536062" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.mingw.base"/> + <tool id="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.debug.1125479542" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.debug"> + <option id="gnu.cpp.compiler.mingw.exe.debug.option.optimization.level.856167253" name="Optimization Level" superClass="gnu.cpp.compiler.mingw.exe.debug.option.optimization.level" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/> + <option id="gnu.cpp.compiler.mingw.exe.debug.option.debugging.level.1286427477" name="Debug Level" superClass="gnu.cpp.compiler.mingw.exe.debug.option.debugging.level" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/> + </tool> + <tool id="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug"> + <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.mingw.exe.debug.option.optimization.level.899548284" name="Optimization Level" superClass="gnu.c.compiler.mingw.exe.debug.option.optimization.level" valueType="enumerated"/> + <option id="gnu.c.compiler.mingw.exe.debug.option.debugging.level.218260318" name="Debug Level" superClass="gnu.c.compiler.mingw.exe.debug.option.debugging.level" value="gnu.c.debugging.level.max" valueType="enumerated"/> + <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.293456763" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/> + </tool> + <tool id="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.debug.237306527" name="MinGW C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.debug"> + <option id="gnu.c.link.option.libs.696325141" name="Libraries (-l)" superClass="gnu.c.link.option.libs" valueType="libs"> + <listOptionValue builtIn="false" value="wsock32"/> + </option> + <option id="gnu.c.link.option.paths.1944619386" name="Library search path (-L)" superClass="gnu.c.link.option.paths" valueType="libPaths"> + <listOptionValue builtIn="false" value="&quot;C:\MinGW32\lib\&quot;"/> + </option> + <inputType id="cdt.managedbuild.tool.gnu.c.linker.input.1057549252" superClass="cdt.managedbuild.tool.gnu.c.linker.input"> + <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> + <additionalInput kind="additionalinput" paths="$(LIBS)"/> + </inputType> + </tool> + <tool id="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.debug.715096099" name="MinGW C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.debug"/> + </toolChain> + </folderInfo> + </configuration> + </storageModule> + <storageModule moduleId="scannerConfiguration"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="makefileGenerator"> + <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827;cdt.managedbuild.config.gnu.mingw.exe.release.1594405827.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424;cdt.managedbuild.tool.gnu.c.compiler.input.191950135"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="makefileGenerator"> + <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458;cdt.managedbuild.config.gnu.mingw.exe.debug.133679458.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703;cdt.managedbuild.tool.gnu.c.compiler.input.293456763"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="makefileGenerator"> + <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + </scannerConfigBuildInfo> + </storageModule> + <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> + </cconfiguration> + <cconfiguration id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827"> + <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827" moduleId="org.eclipse.cdt.core.settings" name="Release"> + <externalSettings/> + <extensions> + <extension id="org.eclipse.cdt.core.PE" point="org.eclipse.cdt.core.BinaryParser"/> + <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> + </extensions> + </storageModule> + <storageModule moduleId="cdtBuildSystem" version="4.0.0"> + <configuration artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.exe" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release,org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.exe" cleanCommand="rm -rf" description="" id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827" name="Release" parent="cdt.managedbuild.config.gnu.mingw.exe.release"> + <folderInfo id="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827." name="/" resourcePath=""> + <toolChain id="cdt.managedbuild.toolchain.gnu.mingw.exe.release.1830096364" name="MinGW GCC" superClass="cdt.managedbuild.toolchain.gnu.mingw.exe.release"> + <targetPlatform id="cdt.managedbuild.target.gnu.platform.mingw.exe.release.199043754" name="Debug Platform" superClass="cdt.managedbuild.target.gnu.platform.mingw.exe.release"/> + <builder buildPath="${workspace_loc:/custom_cs2dsrv/Release}" id="cdt.managedbuild.tool.gnu.builder.mingw.base.781603840" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="CDT Internal Builder" superClass="cdt.managedbuild.tool.gnu.builder.mingw.base"/> + <tool id="cdt.managedbuild.tool.gnu.assembler.mingw.exe.release.1948519560" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.mingw.exe.release"> + <inputType id="cdt.managedbuild.tool.gnu.assembler.input.455298474" superClass="cdt.managedbuild.tool.gnu.assembler.input"/> + </tool> + <tool id="cdt.managedbuild.tool.gnu.archiver.mingw.base.884564668" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.mingw.base"/> + <tool id="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.release.629144444" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.mingw.exe.release"> + <option id="gnu.cpp.compiler.mingw.exe.release.option.optimization.level.1969272803" name="Optimization Level" superClass="gnu.cpp.compiler.mingw.exe.release.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/> + <option id="gnu.cpp.compiler.mingw.exe.release.option.debugging.level.22968446" name="Debug Level" superClass="gnu.cpp.compiler.mingw.exe.release.option.debugging.level" value="gnu.cpp.compiler.debugging.level.none" valueType="enumerated"/> + </tool> + <tool id="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release"> + <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.mingw.exe.release.option.optimization.level.1005366988" name="Optimization Level" superClass="gnu.c.compiler.mingw.exe.release.option.optimization.level" valueType="enumerated"/> + <option id="gnu.c.compiler.mingw.exe.release.option.debugging.level.180917112" name="Debug Level" superClass="gnu.c.compiler.mingw.exe.release.option.debugging.level" value="gnu.c.debugging.level.none" valueType="enumerated"/> + <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.191950135" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/> + </tool> + <tool id="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.release.376579228" name="MinGW C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.mingw.exe.release"> + <option id="gnu.c.link.option.libs.879542908" name="Libraries (-l)" superClass="gnu.c.link.option.libs" valueType="libs"> + <listOptionValue builtIn="false" value="wsock32"/> + </option> + <option id="gnu.c.link.option.paths.599340942" name="Library search path (-L)" superClass="gnu.c.link.option.paths" valueType="libPaths"> + <listOptionValue builtIn="false" value="&quot;C:\MinGW32\lib\&quot;"/> + </option> + <inputType id="cdt.managedbuild.tool.gnu.c.linker.input.465269045" superClass="cdt.managedbuild.tool.gnu.c.linker.input"> + <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> + <additionalInput kind="additionalinput" paths="$(LIBS)"/> + </inputType> + </tool> + <tool id="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.release.963626972" name="MinGW C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.mingw.exe.release"/> + </toolChain> + </folderInfo> + </configuration> + </storageModule> + <storageModule moduleId="scannerConfiguration"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="makefileGenerator"> + <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.release.1594405827;cdt.managedbuild.config.gnu.mingw.exe.release.1594405827.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.release.504501424;cdt.managedbuild.tool.gnu.c.compiler.input.191950135"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="makefileGenerator"> + <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + </scannerConfigBuildInfo> + <scannerConfigBuildInfo instanceId="cdt.managedbuild.config.gnu.mingw.exe.debug.133679458;cdt.managedbuild.config.gnu.mingw.exe.debug.133679458.;cdt.managedbuild.tool.gnu.c.compiler.mingw.exe.debug.1071191703;cdt.managedbuild.tool.gnu.c.compiler.input.293456763"> + <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="makefileGenerator"> + <runAction arguments="-E -P -v -dD" command="" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + <profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC"> + <buildOutputProvider> + <openAction enabled="true" filePath=""/> + <parser enabled="true"/> + </buildOutputProvider> + <scannerInfoProvider id="specsFile"> + <runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/> + <parser enabled="true"/> + </scannerInfoProvider> + </profile> + </scannerConfigBuildInfo> + </storageModule> + <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> + </cconfiguration> + </storageModule> + <storageModule moduleId="cdtBuildSystem" version="4.0.0"> + <project id="custom_cs2dsrv.cdt.managedbuild.target.gnu.mingw.exe.750583817" name="Executable" projectType="cdt.managedbuild.target.gnu.mingw.exe"/> + </storageModule> +</cproject> diff --git a/.project b/.project new file mode 100644 index 0000000..eb3f880 --- /dev/null +++ b/.project @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>custom_cs2dsrv</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name> + <triggers>clean,full,incremental,</triggers> + <arguments> + <dictionary> + <key>?name?</key> + <value></value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.append_environment</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.buildArguments</key> + <value></value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.buildCommand</key> + <value>make</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.buildLocation</key> + <value>${workspace_loc:/custom_cs2dsrv/Debug}</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.contents</key> + <value>org.eclipse.cdt.make.core.activeConfigSettings</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.enableAutoBuild</key> + <value>false</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.enableCleanBuild</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.enableFullBuild</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.stopOnError</key> + <value>true</value> + </dictionary> + <dictionary> + <key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key> + <value>true</value> + </dictionary> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name> + <triggers>full,incremental,</triggers> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.cdt.core.cnature</nature> + <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature> + <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature> + </natures> +</projectDescription> diff --git a/.settings/org.eclipse.cdt.managedbuilder.core.prefs b/.settings/org.eclipse.cdt.managedbuilder.core.prefs new file mode 100644 index 0000000..5cd5819 --- /dev/null +++ b/.settings/org.eclipse.cdt.managedbuilder.core.prefs @@ -0,0 +1,22 @@ +#Tue Oct 12 19:59:12 CEST 2010 +eclipse.preferences.version=1 +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/CPATH/delimiter=; +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/CPATH/operation=remove +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/C_INCLUDE_PATH/delimiter=; +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/C_INCLUDE_PATH/operation=remove +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/append=true +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/appendContributed=true +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/CPATH/delimiter=; +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/CPATH/operation=remove +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/C_INCLUDE_PATH/delimiter=; +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/C_INCLUDE_PATH/operation=remove +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/append=true +environment/buildEnvironmentInclude/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/appendContributed=true +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/LIBRARY_PATH/delimiter=; +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/LIBRARY_PATH/operation=remove +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/append=true +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.debug.133679458/appendContributed=true +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/LIBRARY_PATH/delimiter=; +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/LIBRARY_PATH/operation=remove +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/append=true +environment/buildEnvironmentLibrary/cdt.managedbuild.config.gnu.mingw.exe.release.1594405827/appendContributed=true diff --git a/include/cross_layer.h b/include/cross_layer.h new file mode 100644 index 0000000..934fdd2 --- /dev/null +++ b/include/cross_layer.h @@ -0,0 +1,13 @@ +#ifndef CROSS_LAYER_H_INCLUDED +#define CROSS_LAYER_H_INCLUDED + +#include "main.h" + +int create_socket(void); +void error_exit(char *message); +void bind_socket(int *sock, unsigned long adress, unsigned short port); +void cleanup(void); +int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client); +void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client); +int mtime(void); +#endif // CROSS_LAYER_H_INCLUDED diff --git a/include/functions.h b/include/functions.h new file mode 100644 index 0000000..0ed1900 --- /dev/null +++ b/include/functions.h @@ -0,0 +1,23 @@ +#ifndef FUNCTIONS_H_INCLUDED +#define FUNCTIONS_H_INCLUDED + +#include "main.h" +int IsPlayerKnown(struct in_addr ip, u_short port); +void ClearPlayer(int id); +void ClearAllPlayer(void); +void CheckForTimeout(void); +void GivePlayerWeapon(int id, int wpnid); +void RemovePlayerWeapon(int id, int wpnid); +void RemoveAllPlayerWeapon(int id); +int PlayerTimeout(int id); +unsigned short GetServerStatus(void); +unsigned short endian_swap_short(unsigned short *x); +unsigned int endian_swap_int(unsigned int *x); +int ValidatePaket(char *message, int id); +void PaketConfirmation(char *message, int id, int writesocket); +int CheckPlayerData(char *password); +unsigned char *GetEncodedString(unsigned char *string, int length); + +extern time_t firsttime; + +#endif // FUNCTIONS_H_INCLUDED diff --git a/include/log.h b/include/log.h new file mode 100644 index 0000000..cf3d22a --- /dev/null +++ b/include/log.h @@ -0,0 +1,79 @@ +#ifndef LOG_H_INCLUDED +#define LOG_H_INCLUDED + +#include "main.h" + +void myprintf(char *string, ...); +void myprintf2(char *string, ...); + +/* +#define printf(...) file = fopen("log.txt","a+");\ + time(&rawtime );\ + timeinfo = localtime(&rawtime);\ + fprintf(file, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ + fprintf(file, __VA_ARGS__);\ + printf("[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\ + printf(__VA_ARGS__);\ + fclose(file) + +#define eprintf(...) file = fopen("log.txt","a+");\ + fprintf(file, __VA_ARGS__);\ + fprintf(stdout, __VA_ARGS__);\ + fclose(file) + +extern FILE *file; + +extern time_t rawtime; +extern struct tm * timeinfo; +*/ +#define printf(...) myprintf(__VA_ARGS__) +#define eprintf(...) myprintf2(__VA_ARGS__) + +#endif // LOG_H_INCLUDED + + +/* + if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) + { + if((player[i].x - player[id].x) != 0 && (player[i].y - player[id].y) != 0) + { + float temprot = player[id].rotation; + double angle = atan2(player[i].x - player[id].x, player[i].y - player[id].y) * 180 / PI; + double angle2, angle3; + if(player[id].rotation < 0) + { + temprot += 180; + } + else if(player[id].rotation > 0) + { + temprot -= 180; + } + temprot = temprot *-1; + double victimangle = atan2(player[id].x - player[i].x, player[id].y - player[i].y) * 180 / PI; + double victimangle2 = victimangle + 90; + double victimangle3 = victimangle - 90; + int xPoint1, yPoint1; + int xPoint2, yPoint2; + xPoint1 = player[i].x + 16*cos(victimangle2*PI/180); + yPoint1 = player[i].y + 16*sin(victimangle2*PI/180); + xPoint2 = player[i].x + 16*cos(victimangle3*PI/180); + yPoint2 = player[i].y + 16*sin(victimangle3*PI/180); + + angle2 = atan2(xPoint1 - player[id].x, yPoint1 - player[id].y) * 180 / PI; + angle3 = atan2(xPoint2 - player[id].x, yPoint2 - player[id].y) * 180 / PI; + printf("(Debug2) %lf: %lf, %lf\n", temprot, angle2, angle3); + + xP = xM + r*cos(ß) + yP = yM + r*sin(ß) + + if((temprot <= angle2 && temprot >= angle3) || (temprot >= angle2 && temprot <= angle3)) + { + SendMessageToPlayer(id, "You hit someone!", 1, writesocket); + SendMessageToPlayer(i, "You were hitted by someone!", 1, writesocket); + OnHit(id, i, writesocket); + } + //SendMessageToPlayer(id, "Shooting not implemented yet!", 1, writesocket); + } + + } + */ diff --git a/include/main.h b/include/main.h new file mode 100644 index 0000000..09d1aae --- /dev/null +++ b/include/main.h @@ -0,0 +1,42 @@ +#ifndef MAIN_H_INCLUDED +#define MAIN_H_INCLUDED + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <stdarg.h> //log.h +#include <math.h> //aim +#define PI 3.14159265 + +#ifdef _WIN32 +#include <winsock.h> +#include <io.h> +#else +#include <errno.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netdb.h> +#include <arpa/inet.h> +#include <unistd.h> + +#include <sys/select.h> //for select() +#endif + +/* Self-made includes */ +#include "log.h" +#include "settings.h" +#include "structs.h" +#include "weapons.h" + +#include "cross_layer.h" +#include "functions.h" +#include "sendto_functions.h" +#include "respond_messages.h" +#include "pakets.h" +#include "script-functions.h" +#include "map.h" + + +#endif // MAIN_H_INCLUDED diff --git a/include/map.h b/include/map.h new file mode 100644 index 0000000..36a456a --- /dev/null +++ b/include/map.h @@ -0,0 +1,21 @@ +#ifndef MAP_H_INCLUDED +#define MAP_H_INCLUDED + +#include "main.h" + +void ReadMap(); +unsigned char *ReadLine(FILE *file); +unsigned char ReadByte(FILE *file); +int ReadInt(FILE *file); +#define MAX_SPAWNPOINTS 10 + +unsigned short tspawnx[MAX_SPAWNPOINTS]; +unsigned short tspawny[MAX_SPAWNPOINTS]; +unsigned short tspawncount; + +unsigned short ctspawnx[MAX_SPAWNPOINTS]; +unsigned short ctspawny[MAX_SPAWNPOINTS]; +unsigned short ctspawncount; + + +#endif // MAP_H_INCLUDED diff --git a/include/pakets.h b/include/pakets.h new file mode 100644 index 0000000..679a9d5 --- /dev/null +++ b/include/pakets.h @@ -0,0 +1,28 @@ +#ifndef PAKETS_H_INCLUDED +#define PAKETS_H_INCLUDED + +#include "main.h" +int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position); +int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); +int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id); +int ping_ingame(unsigned char *message, int length, int id, int writesocket); +int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port); +int confirmation_known(unsigned char *message, int length, int id, int writesocket); +int fire(unsigned char *message, int length, int id, int writesocket); +int buy(unsigned char *message, int length, int id, int writesocket); +int rotupdate(unsigned char *message, int length, int id, int writesocket); +int posupdatewalk(unsigned char *message, int length, int id, int writesocket); +int posupdaterun(unsigned char *message, int length, int id, int writesocket); +int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket); +int posrotupdaterun(unsigned char *message, int length, int id, int writesocket); +int respawnrequest(unsigned char *message, int length, int id, int writesocket); +int weaponchange(unsigned char *message, int length, int id, int writesocket); +int teamchange(unsigned char *message, int length, int id, int writesocket); +int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); +int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); +int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket); +int specpos(unsigned char *message, int length, int id, int writesocket); +int chatmessage(unsigned char *message, int length, int id, int writesocket); +int joinroutine_known(unsigned char *message, int length, int id, int writesocket); +int leave(int id, int writesocket); +#endif // PAKETS_H_INCLUDED diff --git a/include/respond_messages.h b/include/respond_messages.h new file mode 100644 index 0000000..0101f42 --- /dev/null +++ b/include/respond_messages.h @@ -0,0 +1,22 @@ +#ifndef RESPOND_MESSAGES_H_INCLUDED +#define RESPOND_MESSAGES_H_INCLUDED +#include "main.h" + +void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket); +void SendFireMessage(int id, int writesocket); +void SendBuyMessage(int id, int wpnid, int writesocket); +void SendHitMessage(int id, int victim, int health, int writesocket); +void SendWeaponChangeMessage(int id, int wpnid, int writesocket); +void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket); +void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket); +void SendRotUpdate(int id, float rotation, int writesocket); +void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket); +void SendMessageToAll(unsigned char *message, int status, int writesocket); +void SendJoinMessage(int id, int writesocket); +void SendLeaveMessage(int id, int writesocket); +void SendChatMessage(int id, unsigned char *message, int team, int writesocket); +void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket); +void PingAllPlayer(int writesocket); + + +#endif // RESPOND_MESSAGES_H_INCLUDED diff --git a/include/script-functions.h b/include/script-functions.h new file mode 100644 index 0000000..d118787 --- /dev/null +++ b/include/script-functions.h @@ -0,0 +1,22 @@ +#ifndef SCRIPT_H_INCLUDED +#define SCRIPT_H_INCLUDED + +#include "main.h" + +int OnJoin(int id, int writesocket); +int OnLeave(int id, int writesocket); +int OnSpecmove(int id, int newx, int newy, int writesocket); +int OnServerStart(); +int OnExit(); +int OnRespawnRequest(int id, int writesocket); +int OnRespawn(int id, int writesocket); +int OnWeaponChangeAttempt(int id, int wpnid, int writesocket); +int OnFire(int id, int writesocket); +int OnHit(int hitter, int victim, int writesocket); +int OnBuy(int id, int wpnid, int writesocket); +int OnKill(int hitter, int victim, int wpnid, int writesocket); +int OnChatMessage(int id, unsigned char *message, int team, int writesocket); +int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket); +int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket); +int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket); +#endif diff --git a/include/sendto_functions.h b/include/sendto_functions.h new file mode 100644 index 0000000..6bd7edb --- /dev/null +++ b/include/sendto_functions.h @@ -0,0 +1,17 @@ +/* + * sendto_functions.h + * + * Created on: 12.10.2010 + * Author: Jeremy + */ + +#ifndef SENDTO_FUNCTIONS_H_ +#define SENDTO_FUNCTIONS_H_ + +#include "main.h" +void SendToPlayer(unsigned char *message, int length, int id, int reliable, int writesocket); +void SendToAll(unsigned char *message, int length, int reliable, int writesocket); +void SendToTeam(unsigned char *message, int length, int reliable, int team, int writesocket); +void SendToAllOther(int id, unsigned char *message, int length, int reliable, int writesocket); + +#endif /* SENDTO_FUNCTIONS_H_ */ diff --git a/include/settings.h b/include/settings.h new file mode 100644 index 0000000..c18b956 --- /dev/null +++ b/include/settings.h @@ -0,0 +1,37 @@ +#ifndef SETTINGS_H_INCLUDED +#define SETTINGS_H_INCLUDED + +#define MAX_BUF 1024 + +/* --- Server Settings --- */ +#define LOCAL_PORT 1994 +#define MAX_CLIENTS 64 +#define TIMEOUT 10 +#define LITTLE_ENDIAN + +extern unsigned char pre_authcode[]; + +extern unsigned char sv_name[]; +extern unsigned char sv_map[]; +extern unsigned int sv_hostport; +extern unsigned short sv_maxplayers; +extern unsigned short sv_fow; +extern unsigned short sv_gamemode; +extern unsigned short sv_friendlyfire; +extern unsigned short sv_usgnonly; +extern unsigned char sv_password[]; +extern unsigned short bot_count; + +extern unsigned short mp_roundtime; +extern unsigned short mp_freezetime; +extern unsigned short mp_c4timer; +extern unsigned short mp_infammo; +extern unsigned short mp_respawndelay; +extern unsigned short mp_specmode; +extern unsigned short onlineplayer; +extern unsigned short mp_startmoney; + +#define STARTWEAPONS_COUNT 1 +extern char startweapons[]; + +#endif // SETTINGS_H_INCLUDED diff --git a/include/structs.h b/include/structs.h new file mode 100644 index 0000000..a373fe6 --- /dev/null +++ b/include/structs.h @@ -0,0 +1,74 @@ +#ifndef STRUCTS_H_INCLUDED +#define STRUCTS_H_INCLUDED + +#include "main.h" + +struct WEAPON +{ + short weapondamage, weapondamage_z1, weapondamage_z2; + short shoottime, reloadtime; + float freq; + short speed; + short slot; + short price; + short range; + short accuracy; + short ammo1, ammo2; + char *name; +}; +struct WEAPON weapons[100]; + +struct PLAYER_WEAPON +{ + short id, slot; + short ammo1, ammo2; +}; + +struct PLAYER +{ + int used; + unsigned short client_nummer; + unsigned short server_nummer; + time_t lastpaket; + unsigned short joinstatus; + + unsigned char *name; + unsigned char *spraylogo; + unsigned char *win; + unsigned short version; + unsigned short *usgn; + unsigned char team; + unsigned char skin; + short deaths, score; + unsigned short x,y; + unsigned char health, armor; + unsigned char actualweapon; + struct PLAYER_WEAPON slot[10]; + float rotation; //-180 to +180 + int specposx, specposy; + unsigned short money; + + short dead; + + int start; + int latency; + + int firetimer; + int zoommode; + + + /* Address*/ + unsigned short port; + struct in_addr ip; +}; +struct PLAYER player[MAX_CLIENTS]; + + +struct TILE +{ + unsigned char mode; + unsigned char tileid; +}; +struct TILE **map; + +#endif // STRUCTS_H_INCLUDED diff --git a/include/weapons.h b/include/weapons.h new file mode 100644 index 0000000..fb2564f --- /dev/null +++ b/include/weapons.h @@ -0,0 +1,8 @@ +#ifndef WEAPONS_H_INCLUDED +#define WEAPONS_H_INCLUDED + +#include "main.h" +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2); +void WeaponInit(); + +#endif // WEAPONS_H_INCLUDED diff --git a/log.txt b/log.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/cross_layer.c b/src/cross_layer.c new file mode 100644 index 0000000..2ea0f41 --- /dev/null +++ b/src/cross_layer.c @@ -0,0 +1,151 @@ +#include "../include/cross_layer.h" + +int create_socket(void) +{ +#ifdef _WIN32 + + WSADATA wsa; + if (WSAStartup (MAKEWORD(2,0), &wsa) != 0) + { + error_exit("WSAStartup() failed"); + } + else + { + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + { + error_exit("socket() failed"); + } + return sock; + } +#else + + const int y = 1; + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + { + error_exit("socket() failed"); + } + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); + return sock; + +#endif + return 0; +} + +void bind_socket(int *sock, unsigned long adress, unsigned short port) +{ +#ifdef _WIN32 + struct sockaddr_in server; + + memset(&server, 0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = htonl(adress); + server.sin_port = htons(port); + if (bind(*sock, (struct sockaddr*) &server, sizeof(server)) == SOCKET_ERROR) + { + error_exit("bind() failed"); + } +#else + struct sockaddr_in server; + memset(&server, 0, sizeof (server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = htonl(adress); + server.sin_port = htons(port); + if (bind(*sock, (struct sockaddr*)&server, sizeof(server)) < 0) + { + error_exit("bind() failed"); + } +#endif +} + +void error_exit(char *message) +{ + printf("%s", message); + /* + printf("%s: %d\n", message, WSAGetLastError()); + //debug(stderr); + #else + printf("%s: %s\n", message, strerror(errno)); + //debug(stderr); + */ + + exit(EXIT_FAILURE); +} + +void cleanup(void) +{ + OnExit(); +#ifdef _WIN32 + WSACleanup(); +#else + /* Nichts zu tun */ +#endif +} + +#ifdef _WIN32 +int mtime(void) +{ + return GetTickCount(); +} +#else +int mtime(void) +{ + struct timeval tv; + gettimeofday(&tv,NULL); + return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); +} +#endif + +void udp_send(int socket, unsigned char *data, int length, struct sockaddr_in *client) +{ + int rc; + + //printf("Try to send message to %s:%d...\n", inet_ntoa(client->sin_addr), client->sin_port); + rc = sendto(socket, data, length, 0, (struct sockaddr *)client, sizeof(*client)); + /* + int i; + for(i = 0; i <= length; i++) + { + printf("%d-", data[i]); + } + printf("\n"); + */ + +#ifdef _WIN32 + if (rc == SOCKET_ERROR) + error_exit("sendto() failed"); +#else + if (rc < 0) + error_exit("sendto() failed"); +#endif + //else + //printf("Message sent!\n"); +} + +int udp_recieve(int socket, unsigned char *data, int length, struct sockaddr_in *client) +{ + struct sockaddr_in newclient; + unsigned int len; + int size; + len = sizeof(struct sockaddr_in); + size = recvfrom(socket, data, length, 0, (struct sockaddr *)&newclient,&len); + *client = newclient; +#ifdef _WIN32 + if (size == SOCKET_ERROR) + { + error_exit("recvfrom() failed"); + } +#else + if (size < 0) + { + error_exit("recvfrom() failed"); + } +#endif + else + { + return size; + } + return 0; +} + diff --git a/src/functions.c b/src/functions.c new file mode 100644 index 0000000..2c6431a --- /dev/null +++ b/src/functions.c @@ -0,0 +1,307 @@ +#include "../include/functions.h" + +int IsPlayerKnown(struct in_addr ip, u_short port) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if ( !strcmp(inet_ntoa(ip), inet_ntoa(player[i].ip)) && port == player[i].port) + { + return i; + } + } + return -1; +} + +void ClearPlayer(int id) +{ + player[id].used = 0; + player[id].client_nummer = 0; + player[id].server_nummer = 0; + player[id].lastpaket = 0; + player[id].joinstatus = 0; + + free(player[id].name); + player[id].name = NULL; + free(player[id].spraylogo); + player[id].spraylogo = NULL; + free(player[id].win); + player[id].win = NULL; + free(player[id].usgn); + player[id].usgn = NULL; + player[id].version = 0; + + player[id].team = 0; + player[id].deaths = 0; + player[id].score = 0; + + player[id].x = 0; + player[id].y = 0; + + player[id].health = 0; + player[id].armor = 0; + + player[id].actualweapon = 0; + + int i; + for(i = 0; i <= 9; i++) + { + player[id].slot[i].id = 0; + } + player[id].rotation = 0; + + player[id].dead = 1; + + player[id].start = 0; + player[id].money = mp_startmoney; + player[id].zoommode = 0; + + /* Address*/ + player[id].port = 0; + //player[id].ip = ""; +} + +void ClearAllPlayer(void) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + ClearPlayer(i); + } +} + +void CheckForTimeout(void) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if (PlayerTimeout(i)) + { + printf("Client %d timed out!\n", i); + ClearPlayer(i); + } + } +} + +void GivePlayerWeapon(int id, int wpnid) +{ + int i; + for(i = 0; i <= 9; i++) + { + if(player[id].slot[i].id == 0) + { + player[id].slot[i].id = wpnid; + player[id].slot[i].slot = weapons[wpnid].slot; + player[id].slot[i].ammo1 = weapons[wpnid].ammo1; + player[id].slot[i].ammo2 = weapons[wpnid].ammo2; + break; + } + } +} + +void RemovePlayerWeapon(int id, int wpnid) +{ + int i; + for(i = 0; i <= 9; i++) + { + if(player[id].slot[i].id == wpnid) + { + player[id].slot[i].id = 0; + player[id].slot[i].slot = 0; + player[id].slot[i].ammo1 = 0; + player[id].slot[i].ammo2 = 0; + break; + } + } +} + +void RemoveAllPlayerWeapon(int id) +{ + int i; + for(i = 0; i <= 9; i++) + { + player[id].slot[i].id = 0; + player[id].slot[i].slot = 0; + player[id].slot[i].ammo1 = 0; + player[id].slot[i].ammo2 = 0; + } +} + +int PlayerTimeout(int id) +{ + id = 0; + /* + time_t actualtime; + time(&actualtime); + + if(((player[id].lastpaket + TIMEOUT) > actualtime) && player[id].lastpaket != 0) + { + printf("POSITIV!\n"); + return 1; + } + */ + return 0; +} + + + +unsigned short GetServerStatus(void) // +{ + unsigned short serverstatus = 0; + if(strcmp(sv_password, "")) + { + serverstatus += 1; + } + if(sv_usgnonly == 1) + { + serverstatus += 2; + } + if(sv_fow == 1) + { + serverstatus += 4; + } + if(sv_friendlyfire == 1) + { + serverstatus += 8; + } + if(1) //Same Version? + { + serverstatus += 16; + } + if(sv_gamemode != 0) + { + serverstatus += 32; + } + if(0) //LuaScripts + { + serverstatus += 64; + } + if(1) //Dedicated + { + serverstatus += 128; + } + return serverstatus; +} + + +unsigned short endian_swap_short(unsigned short *x) +{ + *x = (*x>>8) | + (*x<<8); + return *x; +} + +unsigned int endian_swap_int(unsigned int *x) +{ + *x = (*x>>24) | + ((*x<<8) & 0x00FF0000) | + ((*x>>8) & 0x0000FF00) | + (*x<<24); + return *x; +} + + +int ValidatePaket(char *message, int id) +{ + unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + if(*pTempNummer % 2 != 0) + { + if(((*pTempNummer)+2) < player[id].client_nummer || (*pTempNummer) > (player[id].client_nummer+2)) + { + printf("Invalid paket! (Bad index: %d; expected: %d)\n", *pTempNummer, player[id].client_nummer); + free(pTempNummer); + return 0; + } + } + if(*pTempNummer-1 > player[id].client_nummer) + { + player[id].client_nummer = *pTempNummer; + } + /* + unsigned short *pNummer = &player[id].client_nummer; + pNummer[0] = buffer[0]; + pNummer[1] = buffer[1]; + */ + free(pTempNummer); + return 1; +} + +void PaketConfirmation(char *message, int id, int writesocket) +{ + unsigned short *pTempNummer = malloc(sizeof(unsigned short)); + pTempNummer[0] = message[0]; + pTempNummer[1] = message[1]; + if(*pTempNummer % 2 == 0) + { + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + buffer[0] = 0x01; + memcpy(buffer+1, pTempNummer, 2); + + SendToPlayer(buffer, stringsize, id, 0, writesocket); + + free(buffer); + } + free(pTempNummer); +} + +int CheckPlayerData(char *password) +{ + if(strcmp(sv_password, password) != 0) + { + printf("Password wrong!\n"); + return 1; + } + if(sv_maxplayers == onlineplayer) + { + printf("Server full!\n"); + return 3; + } + /* + 0 - Normal + 1 - Password wrong + 2 - USGN only + 3 - Server full + 4 - Banned + 5 - Another Game Version + 6 - ?? + 7 - Can't validate user (USGN offline) + 8 - ?? + 9 - Connection already exists + 10 - Wrong client (pre_authcode) + 11 - Diffrent map (temp, etc.) + 12 - Map unknown (maptransfer disabled) + 13++ - Failed to join + */ + + return 0; +} + +unsigned char *GetEncodedString(unsigned char *string, int length) +{ + unsigned char *buffer = malloc(length+1); //+1 need for \0 + if (buffer == NULL) error_exit("Memory error ( GetEncodedString() )\n"); + + int i; + for (i = 0; i <= length; i++) + { + if ((i % 3) == 0) + { + buffer[i] = string[i] + 110; + } + else if ((i % 3) == 1) + { + buffer[i] = string[i] + 97; + } + else if ((i % 3) == 2) + { + buffer[i] = string[i] + 109; + } + } + buffer[length] = '\0'; + + return buffer; +} + diff --git a/src/log.c b/src/log.c new file mode 100644 index 0000000..58bb859 --- /dev/null +++ b/src/log.c @@ -0,0 +1,49 @@ +#include "../include/log.h" + +void myprintf(char *string, ...) +{ + FILE *logfile; + time_t rawtime; + struct tm * timeinfo; + + logfile = fopen("log.txt","a+"); + if(logfile != NULL) + { + time(&rawtime); + timeinfo = localtime(&rawtime); + //fprintf(logfile, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + fprintf(stdout, "[%d:%d:%d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); + + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string,argzeiger); + //vfprintf(logfile, string, argzeiger); + va_end(argzeiger); + + fclose(logfile); + } + else + { + printf("Cannot open logfile!\n"); + } +} + +void myprintf2(char *string, ...) +{ + FILE *logfile; + logfile = fopen("log.txt","a+"); + if(logfile != NULL) + { + va_list argzeiger; + va_start(argzeiger,string); + vprintf(string,argzeiger); + //vfprintf(logfile, string, argzeiger); + va_end(argzeiger); + + fclose(logfile); + } + else + { + printf("Cannot open logfile!\n"); + } +} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..6785da2 --- /dev/null +++ b/src/main.c @@ -0,0 +1,188 @@ +#include "../include/main.h" + +time_t firsttime; + +int main() +{ + int readsocket; + struct sockaddr_in newclient; + unsigned char buffer[MAX_BUF]; + int size; + fd_set descriptor; //I don't know + + ClearAllPlayer(); + WeaponInit(); + + readsocket = create_socket(); + bind_socket(&readsocket, INADDR_ANY, LOCAL_PORT); + atexit(cleanup); + + FD_ZERO(&descriptor); + FD_SET(readsocket, &descriptor); + + OnServerStart(); + ReadMap(); + time(&firsttime); + while(1) + { + + CheckForTimeout(); + PingAllPlayer(readsocket); + + select(readsocket+1, &descriptor, NULL, NULL, NULL); + + if(FD_ISSET(readsocket, &descriptor)) + { + size = udp_recieve(readsocket, buffer, MAX_BUF, &newclient); + //printf("(Debug) Recieved data from %s:%d\n", inet_ntoa(newclient.sin_addr), newclient.sin_port); + + if (size < 3) + { + printf("Invalid paket! (size < 3)\n"); + } + else + { + int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port); + if(id != -1) + { + if (ValidatePaket(buffer, id)) + { + PaketConfirmation(buffer, id, readsocket); + time(&player[id].lastpaket); + int control = 1; + int position = 2; + while(control) + { + int tempsize = size - position; + + unsigned char *message = malloc(tempsize); + memcpy(message, buffer+position, tempsize); + int rtn = 0; + + switch(message[0]) //payload + { + case 1: + rtn = confirmation_known(message, tempsize, id, readsocket); + break; + case 3: + rtn = connection_setup_known(message, tempsize, newclient.sin_addr, newclient.sin_port, id); + break; + case 7: + rtn = fire(message, tempsize, id, readsocket); + break; + case 9: + rtn = weaponchange(message, tempsize, id, readsocket); + break; + case 10: + rtn = posupdaterun(message, tempsize, id, readsocket); + break; + case 11: + rtn = posupdatewalk(message, tempsize, id, readsocket); + break; + case 12: + rtn = rotupdate(message, tempsize, id, readsocket); + break; + case 13: + rtn = posrotupdaterun(message, tempsize, id, readsocket); + break; + case 14: + rtn = posrotupdatewalk(message, tempsize, id, readsocket); + break; + case 20: + rtn = teamchange(message, tempsize, id, readsocket); + break; + case 32: + rtn = specpos(message, tempsize, id, readsocket); + break; + case 39: + rtn = respawnrequest(message, tempsize, id, readsocket); + break; + case 240: + rtn = chatmessage(message, tempsize, id, readsocket); + break; + case 249: + rtn = ping_ingame(message, tempsize, id, readsocket); + break; + case 252: + rtn = joinroutine_known(message, tempsize, id, readsocket); + break; + case 253: + rtn = leave(id, readsocket); + break; + default: + SendMessageToPlayer(id, "Not implemented yet!", 1, readsocket); + unknown(message, tempsize, buffer, size, position); + rtn = tempsize; + break; + } + + position = position + rtn; + if (position == size) + { + free(message); + break; + } + else if (position > size) + { + printf("Error while reading packet: position(%d) > size(%d)\n", position, size); + free(message); + } + free(message); + } + } + } + else + { + int control = 1; + int position = 2; + while(control) + { + int tempsize = size - position; + + unsigned char *message = malloc(tempsize); + memcpy(message, buffer+position, tempsize); + int rtn = 0; + + switch(message[0]) //payload + { + case 1: + rtn = confirmation_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); + break; + case 3: + rtn = connection_setup_unknown(message, tempsize, newclient.sin_addr, newclient.sin_port); + break; + case 250: + rtn = ping_serverlist(message, tempsize, &newclient, readsocket); + break; + case 251: + rtn = serverinfo_request(message, tempsize, &newclient, readsocket); + break; + case 252: + rtn = joinroutine_unknown(message, tempsize, &newclient, readsocket); + break; + default: + unknown(message, tempsize, buffer, size, position); + rtn = tempsize; + break; + } + + position = position + rtn; + if (position == size) + { + free(message); + break; + } + else if (position > size) + { + printf("Error while reading packet: position(%d) > size(%d)\n", position, size); + free(message); + } + free(message); + } + } + } + + } + } + return 0; +} diff --git a/src/map.c b/src/map.c new file mode 100644 index 0000000..39e6a9d --- /dev/null +++ b/src/map.c @@ -0,0 +1,171 @@ +#include "../include/map.h" + +void ReadMap() +{ + FILE *file; + int i; + tspawncount = 0; + ctspawncount = 0; + + char *mappath = malloc(strlen(sv_map)+5); + memcpy(mappath, sv_map, strlen(sv_map)); + memcpy(mappath+strlen(sv_map), ".map\0", 5); + + file = fopen(mappath,"rb"); + if(file == NULL) error_exit("Map not found.. Abort\n"); + else printf("Loading '%s'..", mappath); + + free(mappath); + + //------------------------------ + unsigned char *mapheader = ReadLine(file); + for(i = 1; i <= 9; i++) ReadByte(file); + for(i = 1; i <= 10; i++) ReadInt(file); + for(i = 1; i <= 10; i++) ReadLine(file); + unsigned char *code = ReadLine(file); + unsigned char *tileset = ReadLine(file); + unsigned char loaded = ReadByte(file); + int maxx = ReadInt(file); + int maxy = ReadInt(file); + unsigned char *background = ReadLine(file); + int backgroundx = ReadInt(file); + int backgroundy = ReadInt(file); + unsigned char red = ReadByte(file); + unsigned char green = ReadByte(file); + unsigned char blue = ReadByte(file); + unsigned char *mapcheck = ReadLine(file); + //----------------------------------------- + unsigned char *tilemode = malloc(loaded); + if(tilemode == NULL) error_exit("Memory error in ReadMap()\n"); + for(i = 0; i <= loaded; i++) + { + tilemode[i] = ReadByte(file); + } + + map = malloc(maxx * sizeof(struct TILE *)); + if(map == NULL) error_exit("Memory error in ReadMap()\n"); + for(i = 0; i <= maxx; i++) + { + map[i] = malloc(maxy * sizeof(struct TILE *)); + if(map[i] == NULL) error_exit("Memory error in ReadMap()\n"); + int b; + for(b = 0; b <= maxy; b++) + { + unsigned char bytecache = ReadByte(file); + if (bytecache > loaded) + { + bytecache = 0; + } + map[i][b].tileid = bytecache; + map[i][b].mode = tilemode[bytecache]; + //eprintf("%d|%d: %d|%d\n", i, b, map[i][b].tileid, map[i][b].mode); + } + } + //--------------------------------------- + unsigned char enities_count = ReadByte(file); + for(i = 0; i <= enities_count-1; i++) + { + unsigned char *name = ReadLine(file); + unsigned char typ = ReadByte(file); + int x = ReadInt(file); + int y = ReadInt(file); + unsigned char *trigger = ReadLine(file); + + //eprintf("%s (%d): %d|%d by %s\n", name, typ, x, y, trigger); + int b; + for(b = 0; b <= 9; b++) + { + int unknownint = ReadInt(file); + unsigned char *unknown = ReadLine(file); + //eprintf("(%d) %s || ", unknownint, unknown); + free(unknown); + } + + + switch(typ) + { + case 0: + { + tspawnx[tspawncount] = x; + tspawny[tspawncount] = y; + tspawncount++; + break; + } + case 1: + { + ctspawnx[ctspawncount] = x; + ctspawny[ctspawncount] = y; + ctspawncount++; + break; + } + default: + { + break; + } + } + free(name); + free(trigger); + } + + fclose(file); + + eprintf("loaded!\n"); + free(mapheader); + free(code); + free(tileset); + free(background); + free(mapcheck); +} + + +unsigned char *ReadLine(FILE *file) +{ + int position = 0; + char *line = NULL; + char c; + while( (c=fgetc(file)) != 13) + { + if(c == EOF) error_exit("EndOfFile in ReadByte()\n"); + + line = realloc(line, position+1); + if(line == NULL) error_exit("Memory error in ReadLine()\n"); + + line[position] = c; + + position++; + } + + line = realloc(line, position+1); + if(line == NULL) error_exit("Memory error in ReadLine()\n"); + line[position] = '\0'; + position++; + + fgetc(file); //0x0A + + return line; +} + +unsigned char ReadByte(FILE *file) +{ + unsigned char byte = fgetc(file); + if(byte == EOF) error_exit("EndOfFile in ReadByte()\n"); + return byte; +} + +int ReadInt(FILE *file) +{ + unsigned char byte1 = fgetc(file); + if(byte1 == EOF) error_exit("EndOfFile in ReadInt()\n"); + + unsigned char byte2 = fgetc(file); + if(byte2 == EOF) error_exit("EndOfFile in ReadInt()\n"); + + unsigned char byte3 = fgetc(file); + if(byte3 == EOF) error_exit("EndOfFile in ReadInt()\n"); + + unsigned char byte4 = fgetc(file); + if(byte4 == EOF) error_exit("EndOfFile in ReadInt()\n"); + + return (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; +} + diff --git a/src/pakets.c b/src/pakets.c new file mode 100644 index 0000000..4b4e862 --- /dev/null +++ b/src/pakets.c @@ -0,0 +1,1445 @@ +#include "../include/pakets.h" + + +int unknown(unsigned char *message, int length, unsigned char *buffer, int size, int position) +{ + int paketlength = length; + int i; + printf("Unknown packet: "); + for(i = 2; i <= position-1; i++) + { + eprintf("%d-", buffer[i]); + } + eprintf("\n\t"); + for(i = 0; i <= length; i++) + { + eprintf("%d-", message[i]); + } + eprintf("\n"); + return paketlength; +} + +int connection_setup_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) +{ + int paketlength = 3; + if(length < paketlength) + { + printf("Invalid packet (connection_setup_unknown)!\n"); + return length; + } + return paketlength; +} + +int connection_setup_known(unsigned char *message, int length, struct in_addr ip, unsigned short port, int id) +{ + int paketlength = 3; + if(length < paketlength) + { + printf("Invalid packet (connection_setup_known)!\n"); + return length; + } + + return paketlength; +} + +int ping_ingame(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + if(length < paketlength) + { + printf("Invalid packet (ping_ingame)!\n"); + return length; + } + player[id].latency = mtime() - player[id].start; + return paketlength; +} + +int confirmation_unknown(unsigned char *message, int length, struct in_addr ip, unsigned short port) +{ + int paketlength = 3; + if(length < paketlength) + { + printf("Invalid packet (confirmation_unknown)!\n"); + return length; + } + + return paketlength; +} + +int confirmation_known(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 3; + if(length < paketlength) + { + printf("Invalid packet (confirmation_known)!\n"); + return length; + } + return paketlength; +} + +int fire(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 1; + if(length < paketlength) + { + printf("Invalid packet (fire)!\n"); + return length; + } + switch(OnFire(id, writesocket)) + { + case 0: + SendFireMessage(id, writesocket); + break; + case 1: + break; + } + return paketlength; +} + +int buy(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 3; + if(length < paketlength) + { + printf("Invalid packet (buy)!\n"); + return length; + } + + int position = 1; + int wpnid; + + wpnid = message[position]; + position++; + + switch(OnBuy(id, wpnid, writesocket)) + { + case 0: + SendBuyMessage(id, wpnid, writesocket); + break; + case 1: + break; + } + return paketlength; +} + +int rotupdate(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + float temprotation; + if(length < paketlength) + { + printf("Invalid packet (rot_update)!\n"); + return length; + } + memcpy(&temprotation, message+1, sizeof(float)); + if(temprotation >= -180 && temprotation <= 180) + { + //if(temprotation < 0) temprotation += 360; + memcpy(&player[id].rotation, &temprotation, sizeof(float)); + SendRotUpdate(id, player[id].rotation, writesocket); + } + return paketlength; +} + +int posupdatewalk(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + unsigned short tempx; + unsigned short tempy; + if(length < paketlength) + { + printf("Invalid packet (posupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message+1, 2); + memcpy(&tempy, message+3, 2); + switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + SendPosUpdate(id, tempx, tempy, 0, writesocket); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosUpdate(id, player[id].x, player[id].y, 0, writesocket); + break; + default: + break; + } + return paketlength; +} + +int posupdaterun(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 5; + unsigned short tempx; + unsigned short tempy; + if(length < paketlength) + { + printf("Invalid packet (posupdaterun)!\n"); + return length; + } + memcpy(&tempx, message+1, 2); + memcpy(&tempy, message+3, 2); + switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + SendPosUpdate(id, tempx, tempy, 1, writesocket); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosUpdate(id, player[id].x, player[id].y, 1, writesocket); + break; + default: + break; + } + return paketlength; +} + +int posrotupdatewalk(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 9; + unsigned short tempx; + unsigned short tempy; + float rotation; + if(length < paketlength) + { + printf("Invalid packet (posrotupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message+1, 2); + memcpy(&tempy, message+3, 2); + memcpy(&rotation, message+5, sizeof(float)); + + if(rotation >= -180 && rotation <= 180) + { + switch(OnMoveAttempt(id, tempx, tempy, 0, writesocket)) + { + case 0: + //if(rotation < 0) rotation += 360; + SendPosRotUpdate(id, tempx, tempy, 0, rotation, writesocket); + memcpy(&player[id].rotation, &rotation, sizeof(float)); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosRotUpdate(id, player[id].x, player[id].y, 0, player[id].rotation, writesocket); + break; + default: + break; + } + } + return paketlength; +} + +int posrotupdaterun(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 9; + unsigned short tempx; + unsigned short tempy; + float rotation; + if(length < paketlength) + { + printf("Invalid packet (posrotupdatewalk)!\n"); + return length; + } + memcpy(&tempx, message+1, 2); + memcpy(&tempy, message+3, 2); + memcpy(&rotation, message+5, sizeof(float)); + + if(rotation >= -180 && rotation <= 180) + { + switch(OnMoveAttempt(id, tempx, tempy, 1, writesocket)) + { + case 0: + //if(rotation < 0) rotation += 360; + SendPosRotUpdate(id, tempx, tempy, 1, rotation, writesocket); + memcpy(&player[id].rotation, &rotation, sizeof(float)); + player[id].x = tempx; + player[id].y = tempy; + break; + case 1: + SendPosRotUpdate(id, player[id].x, player[id].y, 1, player[id].rotation, writesocket); + break; + default: + break; + } + } + return paketlength; +} + +int respawnrequest(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 1; + if(length < paketlength) + { + printf("Invalid packet (respawnrequest)! (WTF?)\n"); + return length; + } + switch(OnRespawnRequest(id, writesocket)) + { + case 0: + srand(time(NULL)); + switch(player[id].team) + { + case 0: + printf("%s tried to spawn as spectator!\n", player[id].name); + break; + case 1: + { + int tmp = rand() % tspawncount; + printf("%s spawned!\n", player[id].name); + player[id].health = 100; + player[id].dead = 0; + player[id].x = (tspawnx[tmp]+0.5)*32; + player[id].y = (tspawny[tmp]+0.5)*32; + SendSpawnMessage(id, player[id].x, player[id].y, writesocket); + break; + } + case 2: + { + int tmp = rand() % ctspawncount; + printf("%s spawned!\n", player[id].name); + player[id].health = 100; + player[id].dead = 0; + player[id].x = (ctspawnx[tmp]+0.5)*32; + player[id].y = (ctspawny[tmp]+0.5)*32; + SendSpawnMessage(id, player[id].x, player[id].y, writesocket); + break; + } + + } + break; + case 1: + break; + default: + break; + } + return paketlength; +} + +int weaponchange(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 3; + if(length < paketlength) + { + printf("Invalid packet (weaponchange)!\n"); + return length; + } + int position = 1; + int wpnid; + + wpnid = message[position]; + position++; + + switch(OnWeaponChangeAttempt(id, wpnid, writesocket)) + { + case 0: + SendWeaponChangeMessage(id, wpnid, writesocket); + break; + case 1: + break; + default: + break; + } + return paketlength; +} + +int teamchange(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 3; + if(length < paketlength) + { + printf("Invalid packet (teamchange)!\n"); + return length; + } + unsigned char team = message[1]; + unsigned char skin = message[2]; + + switch(OnTeamChangeAttempt(id, team, skin, writesocket)) + { + case 0: + player[id].team = team; + if(skin != 5) player[id].skin = skin; + OnTeamChange(id, team, skin, writesocket); + break; + case 1: + break; + default: + break; + } + return paketlength; +} + +int ping_serverlist(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) +{ + int paketlength = 5; + if(length < paketlength) + { + printf("Invalid packet (ping_serverlist)!\n"); + return length; + } + + unsigned char *tempbuffer = malloc(paketlength); + if(tempbuffer == NULL) error_exit("Memory error ( ping_serverlist() )"); + + + tempbuffer[0] = 0x01; + tempbuffer[1] = 0x00; + memcpy(tempbuffer+2, message, paketlength); + + udp_send(writesocket, tempbuffer, 5, client); + free(tempbuffer); + return paketlength; +} + +int serverinfo_request(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) +{ + int paketlength = length; + if(length < 2) + { + printf("Invalid packet (serverinfo_request)!\n"); + return length; + } + + /* + int i; + printf("serverinfo_request (%d): ", message[0]); + for (i = 1; i <= paketlength; i++) + { + printf("%d-", message[i]); + } + printf("(%d)\n", paketlength); + int joinroutine_known(unsigned char *message, int length, int id, int writesocket) + */ + + int stringsize = 10 + strlen(sv_name) + strlen(sv_map); + if(sv_gamemode != 0) + { + stringsize++; + } + + unsigned char *buffer = malloc(stringsize); + if(buffer == NULL) error_exit("Memory error ( serverinfo_request() )"); + + int position = 0; + buffer[position] = 1; + position++; + buffer[position] = 0; + position++; + buffer[position] = 0xFB; + position++; + buffer[position] = message[1]; + position++; + + switch(message[1]) + { + case 1: + case 2: + /* + if(message[2] == 0) + { + paketlength = 2; + } + else + { + paketlength = 6; + } + */ + paketlength = 4; + + buffer[position] = GetServerStatus(); + position++; + buffer[position] = strlen(sv_name); + position++; + memcpy(buffer+position, sv_name, strlen(sv_name)); + position += strlen(sv_name); + buffer[position] = strlen(sv_map); + position++; + memcpy(buffer+position, sv_map, strlen(sv_map)); + position += strlen(sv_map); + buffer[position] = onlineplayer; + position++; + buffer[position] = sv_maxplayers; + position++; + if(sv_gamemode != 0) + { + buffer[position] = sv_gamemode; + position++; + } + buffer[position] = bot_count; + position++; + udp_send(writesocket, buffer, stringsize, client); + break; + case 4: + break; + case 5: + break; + default: + break; + } + + free(buffer); + + return paketlength; +} + +int joinroutine_unknown(unsigned char *message, int length, struct sockaddr_in *client, int writesocket) +{ + int paketlength = length; //Just 2 char read (message[1]) + if(length < 2) + { + printf("Invalid packet (joinroutine_unknown)!\n"); + return length; + } + switch(message[1]) + { + case 0x00: + { + paketlength = 2; + + int i; + for (i = 1; i <= MAX_CLIENTS; i++) + { + if (player[i].used != 1) + { + player[i].used = 1; + player[i].ip = client->sin_addr; + player[i].port = client->sin_port; + player[i].joinstatus = 1; + player[i].client_nummer = 4; + player[i].server_nummer = 2; + break; + } + } + int stringsize = 5 + strlen(pre_authcode); + unsigned char *buffer = malloc(stringsize); + if(buffer == NULL) error_exit("Memory error ( joinroutine_unknown() )"); + + int position = 0; + buffer[position] = 0x01; + position++; + buffer[position] = 0x00; + position++; + buffer[position] = 0xFC; + position++; + buffer[position] = 0x00; + position++; + buffer[position] = strlen(pre_authcode); + position++; + memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); + + udp_send(writesocket, buffer, stringsize, client); + + free(buffer); + break; + } + default: + printf("Unexpected join data (%d)\n", message[0]); + break; + } + + return paketlength; +} + +int specpos(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 9; + if(paketlength > length) + { + printf("Invalid packet (specpos)!\n"); + return length; + } + int x, y; + + x = (message[4] << 24) | (message[3] << 16) | (message[2] << 8) | message[1]; + y = (message[8] << 24) | (message[7] << 16) | (message[6] << 8) | message[5]; + + switch(OnSpecmove(id, x, y, writesocket)) + { + case 0: + { + player[id].specposx = x; + player[id].specposy = y; + break; + } + case 1: + { + break; + } + } + return paketlength; +} + +int chatmessage(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength=4; + unsigned char team, unknown; + int paketsize; + + if(paketlength > length) + { + printf("Invalid packet (chatmessage)!\n"); + return length; + } + + int position = 0; + position++; + team = message[position]; + position++; + + paketsize = message[position]; + if (paketsize > 255 || paketsize >= (length-position+1)) + { + printf("Message too big\n"); + return length; + } + position++; + paketlength += paketsize; + + unknown = message[position]; + position++; + + unsigned char *string = malloc(paketsize); + if (string == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(string, message+position, paketsize); + string[paketsize] = '\0'; + position += paketsize; + + switch(OnChatMessage(id, string, team, writesocket)) + { + case 0: + break; + default: + printf("Unknown Return value for OnChatMessage()!\n"); + break; + } + + free(string); + + return paketlength; +} + +int joinroutine_known(unsigned char *message, int length, int id, int writesocket) +{ + int paketlength = 2; + if(paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + switch(message[1]) + { + case 0: + { + paketlength = 2; + if(paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + break; + } + case 1: + { + if(player[id].joinstatus == 1) + { + paketlength = 16; // ??? + if(paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + + int position = 2; + //Playername + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("Playername too big\n"); + return length; + } + paketlength += stringsize; + position++; + + player[id].name = malloc(stringsize); + if (player[id].name == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].name, message+position, stringsize); + player[id].name[stringsize] = '\0'; + position += stringsize; //+1 because after it there is a null byte, so ignore it + + //printf("Player %s connected..\n", player[id].name); + + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("Password too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *password = malloc(stringsize); + if (password == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(password, message+position, stringsize); + password[stringsize] = '\0'; + position += stringsize; + + //printf("\tPassword: "); + /* + int i; + for (i = 0; i <= strlen(password); i++) + { + printf("%d-", password[i]); + } + printf("\n"); + */ + + //Encryption String + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("Encryption too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *encryption1 = malloc(stringsize); + if (encryption1 == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(encryption1, message+position, stringsize); + encryption1[stringsize] = '\0'; + position += stringsize; + + //printf("\tEncryptionstring: %s\n", encryption1); + + //Player Version + player[id].version = message[position]; + position++; + //printf("\tVersion: %d\n", player[id].version); + position++; //Null-byte + + + //USGN ID + player[id].usgn = malloc(sizeof(unsigned short)); + if (player[id].usgn == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].usgn, message+position, 2); //sizeof(unsigned short) == 2 + position += 4; //2 bytes + 2 null bytes +#ifdef LITTLE_ENDIAN +#else + *player[id].usgn = endian_swap_short(player[id].usgn); +#endif + //printf("\tUSGN-ID: %u\n", *player[id].usgn); + + + //Spraylogo + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("Spraylogoname too big\n"); + return length; + }; + paketlength += stringsize; + position++; + + player[id].spraylogo = malloc(stringsize); + if (player[id].spraylogo == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].spraylogo, message+position, stringsize); + player[id].spraylogo[stringsize] = '\0'; + position += stringsize; + + //printf("\tSpraylogo: %s\n", player[id].spraylogo); + + + + //Map-Hash + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("Map-Hash too big\n"); + return length; + } + paketlength += stringsize; + position++; + + unsigned char *maphash= malloc(stringsize); + if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(maphash, message+position, stringsize); + maphash[stringsize] = '\0'; + position += stringsize; + + //printf("\tMap-Hash: %s\n", maphash); + + position++; //Nullbyte + + //WIN + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("WIN too big\n"); + return length; + } + paketlength += stringsize; + position++; + + player[id].win= malloc(stringsize); + if (player[id].win == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(player[id].win, message+position, stringsize); + player[id].win[stringsize] = '\0'; + position += stringsize; + + + //printf("\tWIN: %s (%d)\n", player[id].win, strlen(player[id].win)); + + unsigned char *buffer = NULL; + stringsize = 0; + int tempstatus = CheckPlayerData(password); + switch(tempstatus) + { + case 0x00: + stringsize = 6 + strlen(sv_map) + strlen(pre_authcode); + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 2; + position++; + buffer[position] = 0; //Normal + position++; + buffer[position] = id; + position++; + buffer[position] = strlen(sv_map); + position++; + memcpy(buffer+position, sv_map, strlen(sv_map)); + position += strlen(sv_map); + buffer[position] = strlen(pre_authcode); + position++; + memcpy(buffer+position, pre_authcode, strlen(pre_authcode)); + position += strlen(pre_authcode); + player[id].joinstatus = 2; + break; + + default: + { + stringsize = 3; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 2; + position++; + buffer[position] = tempstatus; //Everyone is banned (just for testing) + position++; + player[id].joinstatus = 0; + break; + } + + } + //stringsize = 16 + strlen(sv_map); + + /* + 0 - Normal + 1 - Password wrong + 2 - USGN only + 3 - Server full + 4 - Banned + 5 - Another Game Version + 6 - ?? + 7 - Can't validate user (USGN offline) + 8 - ?? + 9 - Connection already exists + 10 - Wrong client (pre_authcode) + 11 - Diffrent map (temp, etc.) + 12 - Map unknown (maptransfer disabled) + 13++ - Failed to join + */ + + if(stringsize != 0) SendToPlayer(buffer, stringsize, id, 1, writesocket); + + free(encryption1); + free(maphash); + free(buffer); + + onlineplayer++; + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + case 3: + { + if(player[id].joinstatus == 2) + { + int position = 2; + + paketlength = 5; + if(paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + + //Map-Hash + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("Map-Hash too big\n"); + return length; + } + position++; + + unsigned char *maphash = malloc(stringsize); + if (maphash == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(maphash, message+position, stringsize); + maphash[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tMaphash: %s\n", maphash); + + //pre_authcode_respond + stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("pre_authcon_respond too big\n"); + return length; + } + position++; + + unsigned char *pre_authcode_respond = malloc(stringsize); + if (pre_authcode_respond == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(pre_authcode_respond, message+position, stringsize); + pre_authcode_respond[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tpre_authcode_respond: %s\n", pre_authcode_respond); + + //Player Version + unsigned char mapstatus = message[position]; //avoid warning + position++; + //printf("\tMapstatus: %d\n", mapstatus); + + free(pre_authcode_respond); + free(maphash); + + //Respond + stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 4; + position++; + buffer[position] = 0; //CheckPlayerData() + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + player[id].joinstatus = 3; + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + case 5: + { + if(player[id].joinstatus == 3) + { + int position = 2; + + paketlength = 3; + if(paketlength > length) + { + printf("Invalid packet (joinroutine_known)!\n"); + return length; + } + //Map-Hash + int stringsize = message[position]; + if (stringsize > 255 || stringsize >= (length-position+1)) + { + printf("Mapname too big\n"); + return length; + } + position++; + + unsigned char *mapname = malloc(stringsize); + if (mapname == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + memcpy(mapname, message+position, stringsize); + mapname[stringsize] = '\0'; + position += stringsize; + paketlength += stringsize; + + //printf("\tMapname: %s\n", mapname); + + + //----------- ServerData ----------- + + stringsize = 28 + strlen(sv_map) + strlen(sv_name); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 6; + position++; + buffer[position] = 0; //CheckPlayerData() + position++; + + buffer[position] = strlen(sv_map); + position++; + memcpy(buffer+position, sv_map, strlen(sv_map)); + position += strlen(sv_map); + + buffer[position] = strlen(sv_name); + position++; + memcpy(buffer+position, sv_name, strlen(sv_name)); + position += strlen(sv_name); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = sv_friendlyfire; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = mp_roundtime; + position++; + buffer[position] = mp_freezetime; + position++; + buffer[position] = mp_c4timer; + position++; + buffer[position] = 32; //Unknown + position++; + buffer[position] = 124; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 1; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = sv_maxplayers; + position++; + buffer[position] = sv_fow; + position++; + buffer[position] = mp_specmode; + position++; + buffer[position] = sv_gamemode; + position++; + buffer[position] = mp_respawndelay; + position++; + buffer[position] = mp_infammo; + position++; + buffer[position] = 3; //strlen ACK + position++; + buffer[position] = 65; //A + position++; + buffer[position] = 67; //C + position++; + buffer[position] = 75; //K + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- PlayerData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 1; + position++; + buffer[position] = onlineplayer; + position++; + + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if(player[i].used == 1 && player[i].joinstatus >= 1 && i != id) + { + unsigned char *encodedname; + encodedname = GetEncodedString(player[i].name, strlen(player[i].name)); + unsigned short *deaths = &player[i].deaths; + unsigned short tempscore = player[i].deaths + 1000; + unsigned short *score = &tempscore; + + unsigned short tempx = (player[i].x); + unsigned short tempy = (player[i].y); + unsigned short *x = &tempx; + unsigned short *y = &tempy; + + float *ptemprotation = &player[i].rotation; + + int playersize = 25 + strlen(encodedname); + buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + buffer[position] = i; + position++; + + buffer[position] = strlen(encodedname); + position++; + memcpy(buffer+position, encodedname, strlen(encodedname)); + position += strlen(encodedname); + free(encodedname); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = player[i].team; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + /* + buffer[position] = score[0]; //Deaths + position++; + buffer[position] = score[1]; //Deaths + position++; + */ + memcpy(buffer+position, score, 2); + position += 2; + /* + buffer[position] = deaths[0]; //Deaths + position++; + buffer[position] = deaths[1]; //Deaths + position++; + */ + memcpy(buffer+position, deaths, 2); + position += 2; + memcpy(buffer+position, x, 2); + position += 2; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + memcpy(buffer+position, y, 2); + position += 2; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = ptemprotation[0]; //Rotation + position++; + buffer[position] = ptemprotation[1]; //Rotation + position++; + buffer[position] = player[i].health; //Health + position++; + buffer[position] = player[i].armor; //Armor + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = player[i].slot[player[i].actualweapon].id; //Aktuelle Waffe + position++; + buffer[position] = 0; //Unknown + position++; + /* + 01 00 01 00 00 e8 03 00 00 70 00 00 00 70 01 00 00 7d ff 64 00 00 32 00 + 04 00 01 00 00 e8 03 00 00 0c 18 00 00 0c 18 00 00 66 ff 64 00 00 32 00 + 01 00 01 00 00 e8 03 00 00 00 01 00 00 00 01 00 00 12 00 64 00 00 32 00 + 01 00 02 00 00 e8 03 00 00 01 10 00 00 01 10 + e8 03 00 00 12 01 00 00 01 03 + e8 03 00 00 0c 18 00 00 0d 18 00 00 ab 00 64 00 00 1e 00 + e8 03 00 00 10 18 00 00 10 18 00 00 b6 ff 64 c9 00 49 00 + 01 00 01 00 00 4c 04 96 00 10 18 00 00 10 18 00 00 5e ff 64 00 00 02 00 + */ + } + } + if(1) + { + unsigned char *encodedname; + encodedname = GetEncodedString(player[id].name, strlen(player[id].name)); + + int playersize = 25 + strlen(encodedname); + buffer = realloc(buffer, position+1 + playersize); //+1 because e.g. buffer[10] are 11 chars + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + buffer[position] = id; + position++; + + + buffer[position] = strlen(encodedname); + position++; + memcpy(buffer+position, encodedname, strlen(encodedname)); + position += strlen(encodedname); + free(encodedname); + + buffer[position] = 0; //Unknown + position++; + buffer[position] = player[id].team; + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 232; //Unknown + position++; + buffer[position] = 3; //Unknown + position++; + buffer[position] = 0; //Deaths + position++; + buffer[position] = 0; //Deaths + position++; + buffer[position] = 0; //X + position++; + buffer[position] = 0; //X + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Y + position++; + buffer[position] = 0; //Y + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Health + position++; + buffer[position] = 0; //Armor + position++; + buffer[position] = 0; //Unknown + position++; + buffer[position] = 0; //Aktuelle Waffe 50 = Knife + position++; + buffer[position] = 0; //Unknown + position++; + } + + SendToPlayer(buffer, position, id, 1, writesocket); + free(buffer); + + //----------- PlayerData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 1; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- HostageData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 2; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- ItemData ----------- + + /* + fc 07 03 01(1 anzahl) 01(id) 00 4b(waffenid) 0f 00 12 00 (position) 01 (munition ?) 00 00 00 + */ + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 3; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- EnityData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 4; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- DynamicObjectData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 5; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- ProjectileData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 6; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- DynamicObjectImageData ----------- + stringsize = 4; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 7; //third payload + position++; + buffer[position] = 0; + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + //----------- Final ACK ----------- + stringsize = 7; + buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( joinroutine_known() )\n"); + + position = 0; + + buffer[position] = 252; + position++; + buffer[position] = 7; + position++; + buffer[position] = 200; //third payload + position++; + buffer[position] = 3; //strlen ACK + position++; + buffer[position] = 65; //A + position++; + buffer[position] = 67; //C + position++; + buffer[position] = 75; //K + position++; + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + free(buffer); + + player[id].joinstatus = 4; + free(mapname); + + OnJoin(id, writesocket); + } + else + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + default: + { + printf("Unexpected join data (%d) from %s; expected %d\n", message[1], player[id].name, player[id].joinstatus+1); + } + break; + } + + return paketlength; +} + +int leave(int id, int writesocket) +{ + OnLeave(id, writesocket); + + free(player[id].name); + free(player[id].usgn); + free(player[id].spraylogo); + free(player[id].win); + + player[id].name = NULL; + player[id].usgn = NULL; + player[id].spraylogo = NULL; + player[id].win = NULL; + + onlineplayer--; + + ClearPlayer(id); + + return 2; +} diff --git a/src/respond_messages.c b/src/respond_messages.c new file mode 100644 index 0000000..e4271e7 --- /dev/null +++ b/src/respond_messages.c @@ -0,0 +1,484 @@ +#include "../include/respond_messages.h" + + +void SendSpawnMessage(int id, unsigned short x, unsigned short y, int writesocket) +{ + int stringsize = 11; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); + + int position = 0; + + unsigned short *spawnx = &x; + unsigned short *spawny = &y; + unsigned short *pmoney = &player[id].money; + + buffer[position] = 21; + position++; + buffer[position] = id; + position++; + memcpy(buffer+position, spawnx, 2); + position += 2; + memcpy(buffer+position, spawny, 2); + position += 2; + buffer[position] = 50; //Team + position++; + buffer[position] = 0; + position++; + /* + buffer[position] = pmoney[1]; //Money + position++; + buffer[position] = pmoney[0]; // Money + position++; + */ + memcpy(buffer+position, pmoney, 2); + position += 2; + + int i, count; + count = STARTWEAPONS_COUNT;//sizeof(startweapons)/sizeof(startweapons[0]); + buffer[position] = count; + position++; + + buffer = realloc(buffer, stringsize + count); + if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); + + for(i = 0; i <= count-1; i++) + { + buffer[position] = startweapons[i]; + position++; + + GivePlayerWeapon(id, startweapons[i]); + if(startweapons[i] == 50) player[id].actualweapon = i; //else 0 + } + + /* + int count, i; + count = 0; + for(i = 0; i <= 10; i++) + { + if(player[id].slot[i].id != 0) + { + count++; + } + } + buffer[position] = count; //Count + position++; + + buffer = realloc(buffer, stringsize + count); + if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); + + for(i = 0; i <= 10; i++) + { + if(player[id].slot[i].id != 0) + { + buffer[position] = player[id].slot[i].id; + position++; + } + } + */ + + SendToAll(buffer, stringsize + count, 1, writesocket); + + free(buffer); +} + +void SendFireMessage(int id, int writesocket) +{ + int stringsize = 2; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendFireMessage() )\n"); + + int position = 0; + + buffer[position] = 7; + position++; + buffer[position] = id; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendBuyMessage(int id, int wpnid, int writesocket) +{ + int stringsize = 2; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendBuyMessage() )\n"); + + int position = 0; + + buffer[position] = 7; + position++; + buffer[position] = id; + position++; + + //SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendHitMessage(int id, int victim, int health, int writesocket) +{ + int stringsize = 5; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendHitMessage() )\n"); + + int position = 0; + + buffer[position] = 17; + position++; + buffer[position] = id; + position++; + buffer[position] = victim; + position++; + buffer[position] = health; + position++; + buffer[position] = 0; + position++; + + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendWeaponChangeMessage(int id, int wpnid, int writesocket) +{ + int stringsize = 4; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendWeaponChangeMessage() )\n"); + + int position = 0; + + buffer[position] = 9; + position++; + buffer[position] = id; + position++; + buffer[position] = wpnid; + position++; + buffer[position] = 0; + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendPosUpdate(int id, unsigned short x, unsigned short y, int status, int writesocket) +{ + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendSpawnMessage() )\n"); + + int position = 0; + + unsigned short *px = &x; + unsigned short *py = &y; + + if(status == 0) buffer[position] = 11; + else if(status == 1) buffer[position] = 10; + + position++; + buffer[position] = id; + position++; + memcpy(buffer+position, px, 2); + position += 2; + memcpy(buffer+position, py, 2); + position += 2; + + SendToAllOther(id, buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendPosRotUpdate(int id, unsigned short x, unsigned short y, int status, float rotation, int writesocket) +{ + int stringsize = 10; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendPosRotUpdate() )\n"); + + int position = 0; + + unsigned short *px = &x; + unsigned short *py = &y; + //if(rotation > 180) rotation = (rotation - 360); + //unsigned short *protation = &rotation; //2 Bytes cut off + + if(status == 0) buffer[position] = 14; + else if(status == 1) buffer[position] = 13; + + position++; + buffer[position] = id; + position++; + memcpy(buffer+position, px, 2); + position += 2; + memcpy(buffer+position, py, 2); + position += 2; + memcpy(buffer+position, &rotation, 4); + position += 4; + + SendToAllOther(id, buffer, stringsize, 1, writesocket); + + free(buffer); +} + +void SendRotUpdate(int id, float rotation, int writesocket) +{ + int stringsize = 6; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendRotUpdate() )\n"); + + int position = 0; + //if(rotation > 180) rotation = (rotation - 360); + + + buffer[position] = 12; + position++; + buffer[position] = id; + position++; + memcpy(buffer+position, &rotation, sizeof(float)); + + SendToAllOther(id, buffer, stringsize, 1, writesocket); + + free(buffer); +} + + +void SendMessageToPlayer(int id, unsigned char *message, int status, int writesocket) +{ + /* + 1 - Chat + 2 - Screen + 3 - Console + 4 - Crash + */ + int stringsize = 5 + strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = 0; + position++; + buffer[position] = status; + position++; + buffer[position] = strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer+position, message, strlen(message)); + position += strlen(message); + + SendToPlayer(buffer, stringsize, id, 1, writesocket); + + switch(status) + { + case 1: + printf("To %s (Chat): %s\n", player[id].name ,message); + break; + case 2: + printf("To %s (Screen): %s\n", player[id].name ,message); + break; + case 3: + printf("To %s (Console): %s\n", player[id].name ,message); + break; + default: + printf("Unknown status (SendMessageToPlayer())!\n"); + break; + } + + free(buffer); +} + +void SendMessageToAll(unsigned char *message, int status, int writesocket) +{ + /* + 1 - Chat + 2 - Screen + 3 - Console + 4 - Crash + */ + int stringsize = 5 + strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = 0; + position++; + buffer[position] = status; + position++; + buffer[position] = strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer+position, message, strlen(message)); + position += strlen(message); + + SendToAll(buffer, stringsize, 1, writesocket); + + switch(status) + { + case 1: + printf("To All (Chat): %s\n", message); + break; + case 2: + printf("To All (Screen): %s\n", message); + break; + case 3: + printf("To All (Console): %s\n", message); + break; + default: + printf("Unknown status (SendMessageToAll())!\n"); + break; + } + + + free(buffer); +} + + + +void SendJoinMessage(int id, int writesocket) +{ + int stringsize = 4 + strlen(player[id].name); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 248; + position++; + buffer[position] = id; + position++; + buffer[position] = strlen(player[id].name); + position++; + + memcpy(buffer+position, player[id].name, strlen(player[id].name)); + position += strlen(player[id].name); + + buffer[position] = 0; //strlen ACK + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); +} + +void SendLeaveMessage(int id, int writesocket) +{ + if(player[id].joinstatus >= 4) + { + int stringsize = 3; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendLeaveMessage() )\n"); + int position = 0; + + buffer[position] = 253; + position++; + buffer[position] = id; + position++; + buffer[position] = 0; //strlen ACK + position++; + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); + } +} + +void SendChatMessage(int id, unsigned char *message, int team, int writesocket) +{ + int stringsize = 5 + strlen(message); + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendChatMessage() )\n"); + + int position = 0; + + buffer[position] = 240; + position++; + buffer[position] = id; + position++; + buffer[position] = team; + position++; + buffer[position] = strlen(message); + position++; + buffer[position] = 0; + position++; + memcpy(buffer+position, message, strlen(message)); + position += strlen(message); + if(team == 1) + { + SendToAll(buffer, stringsize, 1, writesocket); + } + else if(team == 2) + { + SendToTeam(buffer, stringsize, 1, player[id].team, writesocket); + } + free(buffer); +} + +void SendTeamChangeMessage(int id, unsigned char team, unsigned char skin, int writesocket) +{ + int stringsize = 4; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 20; + position++; + buffer[position] = id; + position++; + buffer[position] = team; + position++; + buffer[position] = skin; + position++; + + + SendToAll(buffer, stringsize, 1, writesocket); + free(buffer); +} + +void PingAllPlayer(int writesocket) +{ + time_t actualtime; + time(&actualtime); + if(actualtime >= (firsttime + 5)) + { + firsttime = actualtime; + int i; + for(i = 1; i <= sv_maxplayers; i++) + { + if(player[i].used == 1 && player[i].joinstatus >= 4) + { + int stringsize = 5; + unsigned char *buffer = malloc(stringsize); + if (buffer == NULL) error_exit("Memory error ( SendJoinMessage() )\n"); + + int position = 0; + + buffer[position] = 249; + position++; + buffer[position] = 0; + position++; + buffer[position] = 32; + position++; + buffer[position] = 191; + position++; + buffer[position] = 0; + position++; + + player[i].start = mtime(); + + SendToPlayer(buffer, stringsize, i, 0, writesocket); + + free(buffer); + } + + } + } +} diff --git a/src/script-functions.c b/src/script-functions.c new file mode 100644 index 0000000..a64803c --- /dev/null +++ b/src/script-functions.c @@ -0,0 +1,331 @@ +#include "../include/script-functions.h" + +/* +int OnJoin(int id, int writesocket) +id - Who joins +Return Values: +0 - OK +*/ +int OnJoin(int id, int writesocket) +{ + SendJoinMessage(id, writesocket); + printf("%s (#%d) has joined the game!\n\tUsing ip %s:%d and usgn-id #%d!\n", player[id].name, id, inet_ntoa(player[id].ip), player[id].port, *player[id].usgn); + return 0; +} + +/* +int OnLeave(int id, int writesocket) +id - Who leaves +Return Values: +0 - OK +*/ +int OnLeave(int id, int writesocket) +{ + SendLeaveMessage(id, writesocket); + printf("%s has left the game!\n", player[id].name); + return 0; +} + +/* +int OnSpecmove(int id, int newx, int newy, int writesocket) +Return Values: +0 - OK +1 - Don't save it +*/ + +int OnSpecmove(int id, int newx, int newy, int writesocket) +{ + return 0; +} + +/* +int OnServerstart() +Return Values: +0 - OK +*/ +int OnServerStart() +{ + time_t rawtime; + time(&rawtime); + printf("********** Server started **********\n"); + printf("%s", ctime(&rawtime)); + return 0; +} + +/* +int OnExit() +Return Values: +0 - OK +*/ +int OnExit() +{ + printf("********** Server Shutdown! **********\n\n\n\n\n"); + return 0; +} + +/* +int OnRespawnRequest(int id, int writesocket) +Return Values: +0 - Respawn +1 - Don't Respawn +*/ +int OnRespawnRequest(int id, int writesocket) +{ + if(player[id].dead == 1) return 0; + else return 1; +} + +/* +int OnRespawn(int id, int writesocket) +Return Values: +0 - OK +*/ +int OnRespawn(int id, int writesocket) +{ + return 0; +} + +/* +int OnRespawn(int id, int writesocket) +Return Values: +0 - OK +*/ +int OnWeaponChangeAttempt(int id, int wpnid, int writesocket) +{ + int i; + for(i = 0; i <= 9; i++) + { + if(player[id].slot[i].id == wpnid) + { + player[id].actualweapon = i; + printf("%s switched to %s (%d)\n", player[id].name, weapons[player[id].slot[player[id].actualweapon].id].name, player[id].slot[player[id].actualweapon].ammo1); + return 0; + } + } + return 1; +} + +/* +int OnFire(int id, int writesocket) +Return Values: +0 - OK +*/ +int OnFire(int id, int writesocket) +{ + short *ammo1 = &player[id].slot[player[id].actualweapon].ammo1; + if(*ammo1 <= 0 && *ammo1 != -1) + { + printf("Not enough ammo!\n"); + return 1; + } + else + { + if(*ammo1 != -1) + { + *ammo1 = *ammo1-1; + } + } +/* + int temptime = mtime(); + printf("Temptime: %d; Firetimer: %d\n", temptime, player[id].firetimer); + if(temptime < player[id].firetimer) + { + printf("Firetimer error!"); + return 1; + } + else + { + player[id].firetimer = mtime() + weapons[player[id].slot[player[id].actualweapon].id].freq; + //printf("(Debug) %d\n", player[id].firetimer); + } +*/ + int i; + int range = weapons[player[id].slot[player[id].actualweapon].id].range; + + int startx = player[id].x; + int starty = player[id].y; + float rotx; + float roty; + float temprot = player[id].rotation; + + short playershit[MAX_CLIENTS] = {0}; + + if(temprot < 0) + { + temprot = 360 - (temprot *-1); + } + temprot = 360 - temprot; + + temprot += 90; + if(temprot > 360) + { + temprot = temprot-360; + } + + rotx = cos((temprot)*PI/180); + roty = sin((temprot)*PI/180); + + for(i = 1; i <= range; i++) + { + startx += i*rotx; + starty -= i*roty; + + int tilex = (int)(startx)/32; + int tiley = (int)(starty)/32; + + if(tilex <= 0 || tiley <= 0) break; + int tilemode = map[tilex][tiley].mode; + if(tilemode == 1 || tilemode == 3 || tilemode == 4) + { + break; + } + + int b; + for(b = 1; b <= sv_maxplayers; b++) + { + if(player[b].used == 1 && player[b].joinstatus >= 4 && b != id && player[b].dead == 0 && playershit[b] == 0 && player[id].team != player[b].team) + { + if(sqrt( (player[b].x - startx)*(player[b].x - startx) + (player[b].y - starty)*(player[b].y - starty) ) <= 16) + { + OnHit(id, b, writesocket); + playershit[b] = 1; + } + } + } + } + return 0; +} +/* +int OnHit(int hitter, int victim, int writesocket) +Return Values: +0 - OK +*/ +int OnHit(int hitter, int victim, int writesocket) +{ + int wpnid = player[hitter].slot[player[hitter].actualweapon].id; + int damage; + switch(player[hitter].zoommode) + { + case 0: + damage = weapons[wpnid].weapondamage; + break; + case 1: + damage = weapons[wpnid].weapondamage_z1; + break; + case 2: + damage = weapons[wpnid].weapondamage_z2; + break; + default: + damage = weapons[wpnid].weapondamage; + break; + } + if(player[victim].health - damage > 0) + { + player[victim].health -= damage; + SendHitMessage(victim, hitter, player[victim].health, writesocket); + //printf("%s hitted %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); + } + else + { + OnKill(hitter, victim, wpnid, writesocket); + } + + return 0; +} + +int OnBuy(int id, int wpnid, int writesocket) +{ + if(player[id].money - weapons[wpnid].price >= 0) + { + player[id].money -= weapons[wpnid].price; + return 0; + } + return 1; +} + +int OnKill(int hitter, int victim, int wpnid, int writesocket) +{ + player[victim].health = 0; + player[victim].dead = 1; + RemoveAllPlayerWeapon(victim); + SendHitMessage(victim, hitter, player[victim].health, writesocket); + printf("%s killed %s with %s\n", player[hitter].name, player[victim].name, weapons[wpnid].name); + return 0; +} +/* +int OnChatMessage(int id, unsigned char *message, int team, int writesocket) +Return Values: +0 - OK +*/ +int OnChatMessage(int id, unsigned char *message, int team, int writesocket) +{ + if(team == 1) + { + printf("%s: %s\n", player[id].name, message); + } + else if(team == 2) + { + printf("%s (Team): %s\n", player[id].name, message); + } + SendChatMessage(id, message, team, writesocket); + return 0; +} + +/* +int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) +Return Values: +0 - OK +1 - Don't join +*/ +int OnTeamChangeAttempt(int id, unsigned char team, unsigned char skin, int writesocket) +{ + return 0; +} + +/* +int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) +Return Values: +0 - OK +*/ +int OnTeamChange(int id, unsigned char team, unsigned char skin, int writesocket) +{ + if(skin != 5) + { + switch(team) + { + case 0: + printf("%s is now spectator\n", player[id].name); + break; + case 1: + printf("%s is now terrorist\n", player[id].name); + break; + case 2: + printf("%s is now counter-terrorist\n", player[id].name); + break; + default: + printf("%s joined a unknown team\n", player[id].name); + break; + } + } + if(team <= 2) + { + SendTeamChangeMessage(id, team, skin, writesocket); + } + return 0; +} + +/* +int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) +Return Values: +0 - OK +1 - Don't move +*/ +int OnMoveAttempt(int id, unsigned short x, unsigned short y, int status, int writesocket) +{ + /* + int newx = (int)ceil((x)/32); + int newy = (int)ceil((y)/32); + printf("(Debug) Tilemode: %d\n", map[newx][newy].mode); + */ + return 0; +} diff --git a/src/sendto_functions.c b/src/sendto_functions.c new file mode 100644 index 0000000..a87f369 --- /dev/null +++ b/src/sendto_functions.c @@ -0,0 +1,65 @@ +#include "../include/sendto_functions.h" + +void SendToPlayer(unsigned char *message, int length, int id, int reliable, int writesocket) +{ + struct sockaddr_in tempclient; + tempclient.sin_family = AF_INET; + tempclient.sin_port = player[id].port; + tempclient.sin_addr = player[id].ip; + unsigned char *buffer = malloc(length + 2); + if (buffer == NULL) error_exit("Memory error ( SendToPlayer() )"); + + if(reliable == 1) + { + unsigned short *pNummer = &player[id].server_nummer; + memcpy(buffer, pNummer, sizeof(unsigned short)); + player[id].server_nummer += 2; + } + else if(reliable == 0) + { + player[id].server_nummer--; + unsigned short *pNummer = &player[id].server_nummer; + memcpy(buffer, pNummer, sizeof(unsigned short)); + player[id].server_nummer++; + } + memcpy(buffer+2, message, length); + udp_send(writesocket, buffer, length+2, &tempclient); +} + +void SendToAll(unsigned char *message, int length, int reliable, int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if(player[i].used == 1 && player[i].joinstatus >= 4) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } +} + +void SendToTeam(unsigned char *message, int length, int reliable, int team, int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if(player[i].used == 1 && player[i].joinstatus >= 4 && player[i].team == team) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } +} + + + +void SendToAllOther(int id, unsigned char *message, int length, int reliable, int writesocket) +{ + int i; + for (i = 1; i <= sv_maxplayers; i++) + { + if(player[i].used == 1 && player[i].joinstatus >= 4 && i != id) + { + SendToPlayer(message, length, i, reliable, writesocket); + } + } +} \ No newline at end of file diff --git a/src/settings.c b/src/settings.c new file mode 100644 index 0000000..39b9384 --- /dev/null +++ b/src/settings.c @@ -0,0 +1,25 @@ +#include "../include/settings.h" + +unsigned char pre_authcode[] = "5TWs3Obv7"; + +unsigned char sv_name[] = "Alpha Custom CS2D Server"; +unsigned char sv_map[] = "de_cs2d"; +unsigned int sv_hostport = 1994; +unsigned short sv_maxplayers = 32; +unsigned short sv_fow = 0; +unsigned short sv_gamemode = 2; +unsigned short sv_friendlyfire = 0; +unsigned short sv_usgnonly = 0; +unsigned char sv_password[] = ""; +unsigned short bot_count = 0; + +unsigned short mp_roundtime = 5; +unsigned short mp_freezetime = 0; +unsigned short mp_c4timer = 35; +unsigned short mp_infammo = 0; +unsigned short mp_respawndelay = 0; +unsigned short mp_specmode = 1; +unsigned short onlineplayer = 0; +unsigned short mp_startmoney = 65000; + +char startweapons[] = {50}; diff --git a/src/weapons.c b/src/weapons.c new file mode 100644 index 0000000..00fca6a --- /dev/null +++ b/src/weapons.c @@ -0,0 +1,28 @@ +#include "../include/weapons.h" + +void AddWeapon(short id, char name[], short wpndmg, short wpndmg_z1, short wpndmg_z2, short freq, short speed, short slot, short price, short range, short accuracy, short ammo1, short ammo2) +{ + weapons[id].name = malloc(strlen(name)+1); + if(weapons[id].name == NULL) error_exit("Memory Error in AddWeapon()\n"); + strncpy(weapons[id].name, name, strlen(name)+1); + weapons[id].weapondamage = wpndmg; + weapons[id].weapondamage_z1 = wpndmg_z1; + weapons[id].weapondamage_z2 = wpndmg_z2; + weapons[id].freq = freq; + weapons[id].speed = speed; + weapons[id].slot = slot; + weapons[id].price = price; + weapons[id].range = range; + weapons[id].accuracy = accuracy; + weapons[id].ammo1 = ammo1; + weapons[id].ammo2 = ammo2; +} +void WeaponInit() +{ + AddWeapon(1, "USP" , 24 , 0, 0, 166 , 1, 2, 500, 300, 0 , 12, 100); + AddWeapon(2, "Glock" , 21 , 0, 0, 166 , 1, 2, 400, 250, 0 , 20, 120); + AddWeapon(3, "Deagle", 34 , 0, 0, 100 , 1, 2, 550, 300, 0 , 7 , 35 ); + AddWeapon(50, "Knife", 100, 0, 0, 1 , 1, 2, 0 , 8 , 0 , -1, -1 ); +} + +
pawelkaczor/pawelkaczor.github.com
ade99432af488e86e02bccaf6476a6afd65b0e27
Set theme jekyll-theme-time-machine
diff --git a/_config.yml b/_config.yml index c741881..ddeb671 100644 --- a/_config.yml +++ b/_config.yml @@ -1 +1 @@ -theme: jekyll-theme-slate \ No newline at end of file +theme: jekyll-theme-time-machine \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
3e51cf7bf8a7f0e5402e478859a4b9ce32813522
add Readme
diff --git a/README.md b/README.md new file mode 100644 index 0000000..08882c4 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Welcome to my Github site! \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
8e879606dae186dd0ab947767dfc92790d8f1279
remove old content
diff --git a/_config.yml b/_config.yml index fac8013..c741881 100644 --- a/_config.yml +++ b/_config.yml @@ -1,11 +1 @@ ---- -permalink: /:year/:month/:day/:title -lsi: false -markdown: kramdown -highlighter: rouge -comments: true -pretty_style: html_extension -auto: true -server_port: 4000 - theme: jekyll-theme-slate \ No newline at end of file diff --git a/_includes/google-analytics.html b/_includes/google-analytics.html deleted file mode 100644 index 7dde4bf..0000000 --- a/_includes/google-analytics.html +++ /dev/null @@ -1,13 +0,0 @@ -<script type="text/javascript"> - - var _gaq = _gaq || []; - _gaq.push(['_setAccount', 'UA-19004267-1']); - _gaq.push(['_trackPageview']); - - (function() { - var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; - var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); - })(); - -</script> diff --git a/_includes/menubar.html b/_includes/menubar.html deleted file mode 100644 index ddca0a6..0000000 --- a/_includes/menubar.html +++ /dev/null @@ -1,11 +0,0 @@ -<a href="/">home</a> -&middot; <a href="/about.html">o mnie</a> -&middot; <a href="/portfolio.html">portfolio</a> -&middot; <a href="http://github.com/pawelkaczor">na github</a> -&middot; <a href="http://pl.linkedin.com/in/Newicom">na linkedin</a> -&middot; <a href="http://twitter.com/Newion">na twitter</a> -<br /><br /> -<a class="name" href="/"><span>Newion</span></a> -<br /> -Jeśli jeszcze nie zwariowałeś to znaczy, że jesteś niedoinformowany! - diff --git a/_includes/post-div.html b/_includes/post-div.html deleted file mode 100644 index 875c563..0000000 --- a/_includes/post-div.html +++ /dev/null @@ -1,12 +0,0 @@ -{% if page.post-type %}<div class="{{ page.post-type }}">{% else %}<div class="post">{% endif %} - <div class="content"> - <h2 class="title"><a href="{{ page.url }}">{{ page.title }}</a></h2> - {{ body }} - </div>{% unless page.hide_meta %} - <div class="meta"> - <span class="author"><a href="http://newicom.pl">Pawel Kaczor</a></span> &middot; - <span class="date"><a href="/{{ page.date | date: "%Y" }}/{{ page.date | date: "%m" }}">{{ page.date | date: "%e" | ordinalize }} {{ page.date | date: "%B"}} {{ page.date | date: "%Y"}}</a></span> - <span class="tags">{% for tag in page.categories %} &middot; <a href="/{{tag}}.html" rel="tag">{{tag}}</a>{% endfor %}</span> - <span class="tags">&middot; <a href="{{ page.url }}/#disqus_thread" rel="tag">Komentuj</a></span> - </div>{% endunless %} -</div> diff --git a/_layouts/default.html b/_layouts/default.html deleted file mode 100644 index 7c5c55d..0000000 --- a/_layouts/default.html +++ /dev/null @@ -1,49 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>{{ page.title }} &middot; newicom.pl</title>{% if page.description %} - <meta name="description" content="{{ page.description }}"/>{% endif %}{% if page.robots %} - <meta name="robots" content="{{ page.robots }}"/>{% endif %} - <meta name="verify-v1" content="" /> - <meta http-equiv="content-type" content="text/html; charset=utf-8" /> - <meta http-equiv="X-UA-Compatible" content="chrome=1" /> - <link rel="stylesheet" href="/css/style.css" type="text/css" /> - <link rel="stylesheet" href="/css/syntax.css" type="text/css" /> - <link rel="alternate" type="application/atom+xml" href="http://newicom.pl/atom.xml" /> - <link rel="canonical" href="http://newicom.pl{{ page.url }}"/> - <link rel="icon" href="favicon.ico" type="image/x-icon" /> - <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> - <meta name="viewport" content="width=850" /> - <meta name="description" content="Paweł Kaczor - Blog o programowaniu." /> - <meta name="keywords" content="Paweł Kaczor, Pawel Kaczor, Scala, Programowanie, DevBlog, Consulting" /> - <script src="/js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> - <script src="/js/loopedslider.js" type="text/javascript" charset="utf-8"></script> -</head> -<body> - - <div id="container"> - <div id="header" class="menubar"> - {% include menubar.html %} - </div> - <div id="main"> - {{ content }} - </div> - </div> - {% unless page.hide_analytics %}{% include google-analytics.html %}{% endunless %} - <script type="text/javascript"> - //<![CDATA[ - (function() { - var links = document.getElementsByTagName('a'); - var query = '?'; - for(var i = 0; i < links.length; i++) { - if(links[i].href.indexOf('#disqus_thread') >= 0) { - query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; - } - } - document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/Newion/get_num_replies.js' + query + '"></' + 'script>'); - })(); - //]]> - </script> -</body> -</html> diff --git a/_layouts/post.html b/_layouts/post.html deleted file mode 100644 index a0c34e2..0000000 --- a/_layouts/post.html +++ /dev/null @@ -1,8 +0,0 @@ ---- -layout: default ---- -{% assign body = content %} -{% include post-div.html %} -{% unless page.hide_meta %} -<div id="disqus_thread"></div><script type="text/javascript" src="http://disqus.com/forums/Newion/embed.js"></script><noscript><a href="http://disqus.com/forums/Newion/?url=ref">View the discussion thread.</a></noscript><a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a> -{% endunless %} diff --git a/favicon.ico b/favicon.ico deleted file mode 100644 index a6b607d..0000000 Binary files a/favicon.ico and /dev/null differ diff --git a/js/jquery-1.3.2.min.js b/js/jquery-1.3.2.min.js deleted file mode 100644 index b1ae21d..0000000 --- a/js/jquery-1.3.2.min.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * jQuery JavaScript Library v1.3.2 - * http://jquery.com/ - * - * Copyright (c) 2009 John Resig - * Dual licensed under the MIT and GPL licenses. - * http://docs.jquery.com/License - * - * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) - * Revision: 6246 - */ -(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); -/* - * Sizzle CSS Selector Engine - v0.9.3 - * Copyright 2009, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/js/loopedslider.js b/js/loopedslider.js deleted file mode 100644 index e9b4420..0000000 --- a/js/loopedslider.js +++ /dev/null @@ -1,253 +0,0 @@ -/* - * loopedSlider 0.5.5 - jQuery plugin - * written by Nathan Searles - * http://nathansearles.com/loopedslider/ - * - * Copyright (c) 2009 Nathan Searles (http://nathansearles.com/) - * Dual licensed under the MIT (MIT-LICENSE.txt) - * and GPL (GPL-LICENSE.txt) licenses. - * - * Built for jQuery library - * http://jquery.com - * Compatible with jQuery 1.3+ - * - */ - -/* - * markup example for $("#loopedSlider").loopedSlider(); - * - * <div id="loopedSlider"> - * <div class="container"> - * <div class="slides"> - * <div><img src="01.jpg" alt="" /></div> - * <div><img src="02.jpg" alt="" /></div> - * <div><img src="03.jpg" alt="" /></div> - * <div><img src="04.jpg" alt="" /></div> - * </div> - * </div> - * <a href="#" class="previous">previous</a> - * <a href="#" class="next">next</a> - * </div> - * -*/ - -(function($) { - $.fn.loopedSlider = function(options) { - - var defaults = { - container: ".container", //Class/id of main container. You can use "#container" for an id. - slides: ".slides", //Class/id of slide container. You can use "#slides" for an id. - pagination: "pagination", //Class name of parent ul for numbered links. Don't add a "." here. - containerClick: true, //Click slider to goto next slide? true/false - autoStart: 0, //Set to positive number for true. This number will be the time between transitions. - restart: 0, //Set to positive number for true. Sets time until autoStart is restarted. - slidespeed: 300, //Speed of slide animation, 1000 = 1second. - fadespeed: 200, //Speed of fade animation, 1000 = 1second. - autoHeight: 0, //Set to positive number for true. This number will be the speed of the animation. - addPagination: false //Add pagination links based on content? true/false - }; - - this.each(function() { - var obj = $(this); - var o = $.extend(defaults,options); - var distance = 0; - var times = 1; - var slides = $(o.slides,obj).children().size(); - var width = $(o.slides,obj).children().outerWidth(); - var position = 0; - var active = false; - var number = 0; - var interval = 0; - var restart = 0; - var pagination = $("."+o.pagination+" li a",obj); - - if(o.addPagination && !$(pagination).length){ - var buttons = slides; - $(obj).append("<ul class="+o.pagination+">"); - $(o.slides,obj).children().each(function(){ - if (number<buttons) { - $("."+o.pagination,obj).append("<li><a rel="+(number+1)+" href=\"#\" >"+(number+1)+"</a></li>"); - number = number+1; - } else { - number = 0; - return false; - } - $("."+o.pagination+" li a:eq(0)",obj).parent().addClass("active"); - }); - pagination = $("."+o.pagination+" li a",obj); - } else { - $(pagination,obj).each(function(){ - number=number+1; - $(this).attr("rel",number); - $(pagination.eq(0),obj).parent().addClass("active"); - }); - } - - if (slides===1) { - $(o.slides,obj).children().css({position:"absolute",left:position,display:"block"}); - return; - } - - $(o.slides,obj).css({width:(slides*width)}); - - $(o.slides,obj).children().each(function(){ - $(this).css({position:"absolute",left:position,display:"block"}); - position=position+width; - }); - - $(o.slides,obj).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width}); - - if (slides>3) { - $(o.slides,obj).children(":eq("+(slides-1)+")").css({position:"absolute",left:-width}); - } - - if(o.autoHeight){autoHeight(times);} - - $(".next",obj).click(function(){ - if(active===false) { - animate("next",true); - if(o.autoStart){ - if (o.restart) {autoStart();} - else {clearInterval(sliderIntervalID);} - } - } return false; - }); - - $(".previous",obj).click(function(){ - if(active===false) { - animate("prev",true); - if(o.autoStart){ - if (o.restart) {autoStart();} - else {clearInterval(sliderIntervalID);} - } - } return false; - }); - - if (o.containerClick) { - $(o.container,obj).click(function(){ - if(active===false) { - animate("next",true); - if(o.autoStart){ - if (o.restart) {autoStart();} - else {clearInterval(sliderIntervalID);} - } - } return false; - }); - } - - $(pagination,obj).click(function(){ - if ($(this).parent().hasClass("active")) {return false;} - else { - times = $(this).attr("rel"); - $(pagination,obj).parent().siblings().removeClass("active"); - $(this).parent().addClass("active"); - animate("fade",times); - if(o.autoStart){ - if (o.restart) {autoStart();} - else {clearInterval(sliderIntervalID);} - } - } return false; - }); - - if (o.autoStart) { - sliderIntervalID = setInterval(function(){ - if(active===false) {animate("next",true);} - },o.autoStart); - function autoStart() { - if (o.restart) { - clearInterval(sliderIntervalID,interval); - clearTimeout(restart); - restart = setTimeout(function() { - interval = setInterval( function(){ - animate("next",true); - },o.autoStart); - },o.restart); - } else { - sliderIntervalID = setInterval(function(){ - if(active===false) {animate("next",true);} - },o.autoStart); - } - }; - } - - function current(times) { - if(times===slides+1){times = 1;} - if(times===0){times = slides;} - $(pagination,obj).parent().siblings().removeClass("active"); - $(pagination+"[rel='" + (times) + "']",obj).parent().addClass("active"); - }; - - function autoHeight(times) { - if(times===slides+1){times=1;} - if(times===0){times=slides;} - var getHeight = $(o.slides,obj).children(":eq("+(times-1)+")",obj).outerHeight(); - $(o.container,obj).animate({height: getHeight},o.autoHeight); - }; - - function animate(dir,clicked){ - active = true; - switch(dir){ - case "next": - times = times+1; - distance = (-(times*width-width)); - current(times); - if(o.autoHeight){autoHeight(times);} - if(slides<3){ - if (times===3){$(o.slides,obj).children(":eq(0)").css({left:(slides*width)});} - if (times===2){$(o.slides,obj).children(":eq("+(slides-1)+")").css({position:"absolute",left:width});} - } - $(o.slides,obj).animate({left: distance}, o.slidespeed,function(){ - if (times===slides+1) { - times = 1; - $(o.slides,obj).css({left:0},function(){$(o.slides,obj).animate({left:distance})}); - $(o.slides,obj).children(":eq(0)").css({left:0}); - $(o.slides,obj).children(":eq("+(slides-1)+")").css({ position:"absolute",left:-width}); - } - if (times===slides) $(o.slides,obj).children(":eq(0)").css({left:(slides*width)}); - if (times===slides-1) $(o.slides,obj).children(":eq("+(slides-1)+")").css({left:(slides*width-width)}); - active = false; - }); - break; - case "prev": - times = times-1; - distance = (-(times*width-width)); - current(times); - if(o.autoHeight){autoHeight(times);} - if (slides<3){ - if(times===0){$(o.slides,obj).children(":eq("+(slides-1)+")").css({position:"absolute",left:(-width)});} - if(times===1){$(o.slides,obj).children(":eq(0)").css({position:"absolute",left:0});} - } - $(o.slides,obj).animate({left: distance}, o.slidespeed,function(){ - if (times===0) { - times = slides; - $(o.slides,obj).children(":eq("+(slides-1)+")").css({position:"absolute",left:(slides*width-width)}); - $(o.slides,obj).css({left: -(slides*width-width)}); - $(o.slides,obj).children(":eq(0)").css({left:(slides*width)}); - } - if (times===2 ) $(o.slides,obj).children(":eq(0)").css({position:"absolute",left:0}); - if (times===1) $(o.slides,obj).children(":eq("+ (slides-1) +")").css({position:"absolute",left:-width}); - active = false; - }); - break; - case "fade": - times = [times]*1; - distance = (-(times*width-width)); - current(times); - if(o.autoHeight){autoHeight(times);} - $(o.slides,obj).children().fadeOut(o.fadespeed, function(){ - $(o.slides,obj).css({left: distance}); - $(o.slides,obj).children(":eq("+(slides-1)+")").css({left:slides*width-width}); - $(o.slides,obj).children(":eq(0)").css({left:0}); - if(times===slides){$(o.slides,obj).children(":eq(0)").css({left:(slides*width)});} - if(times===1){$(o.slides,obj).children(":eq("+(slides-1)+")").css({ position:"absolute",left:-width});} - $(o.slides,obj).children().fadeIn(o.fadespeed); - active = false; - }); - break; - default: - break; - } - }; - }); - }; -})(jQuery); \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
12531a8a4320004f860cb092bd4c7e7f16407f7b
Set theme jekyll-theme-slate
diff --git a/_config.yml b/_config.yml index 443bd33..fac8013 100644 --- a/_config.yml +++ b/_config.yml @@ -1,9 +1,11 @@ --- permalink: /:year/:month/:day/:title lsi: false markdown: kramdown highlighter: rouge comments: true pretty_style: html_extension auto: true server_port: 4000 + +theme: jekyll-theme-slate \ No newline at end of file
pawelkaczor/pawelkaczor.github.com
37948911456ce7d0f60223ed760f744cf563d3a9
fix mr grep
diff --git a/_posts/mr-vcsh-prezto-user-guide.md b/_posts/mr-vcsh-prezto-user-guide.md index 88def18..b99f826 100644 --- a/_posts/mr-vcsh-prezto-user-guide.md +++ b/_posts/mr-vcsh-prezto-user-guide.md @@ -1,119 +1,117 @@ # myrepos && vcsh && prezto - User Guide This document serves as a single source of information related to configuration of **myrepos & vcsh & prezto (zsh)** combo. # myrepos https://github.com/joeyh/myrepos **mr** - a tool to manage all your version control repos **mr** is configured by .mrconfig file, which list the repositories. **mr** supports vcsh repositories! ### vcsh repository configuration file - example ``` [$HOME/.config/vcsh/repo.d/documents.git] checkout = vcsh clone $DOCUMENTS_GIT_REPO documents vcsh_status = vcsh documents status ~/Documents -grep = ack-grep "$@" +grep = cd "$HOME"; vcsh list-tracked-by documents | xargs -d '\n' ack-grep "$@" ``` --- * **Note** - **mr grep** will not work for vcsh repository unless the **grep** command is defined (as shown above). - - Make sure **ack-grep** is installed. + **mr grep** will not work for vcsh repository unless the **grep** command is defined (as shown above). Make sure **ack-grep** is installed. Leave empty line at the end of the repo configuration file! This is necessary because the repo configs are **included** from the ~/.mrconfig file. Define **vcsh_status** only if you do not generate .gitignore file (see vcsh section for more details). --- ### Less known mr commands - **mr ci** - Commits changes to each repository. (By default, changes are pushed to the remote repository too, when using distributed systems like git) The optional -m parameter allows specifying a commit message. # vcsh https://github.com/RichiH/vcsh vcsh - Version Control System for $HOME - multiple Git repositories in $HOME >> vcsh was designed with myrepos, a tool to manage Multiple Repositories, in mind and the two integrate very nicely. The myrepos tool (mr) has native support for vcsh repositories vcsh repositories are by default located under **$XDG_CONFIG_HOME/vcsh/repo.d** ### Ignored files >> vcsh can generate per-repo .gitignore files (in .gitignore.d/<repo_name>) by running vcsh write-gitignore <repo_name>. That will cause each git repo to ignore anything that is not specifically tracked in itself. This covers not only the git status use case but a few others as well. --- * **Note** Do not run **vcsh write-gitignore** for a repo if you expect new files to arrive often in that repo. If you do not generate .gitignore file for a repo, make sure you define **vcsh_status** command (see mr section above). Otherwise **mr st** and **vcsh status** commands will report many untracked files (because different git repos share the same ($HOME) working directory) - if I remember correctly. Once you run **vcsh write-gitignore** for a repo, newly added files will not be tracked automatically! You will have to add them manually to the repo!. The git add command can be used to add ignored files with the -f (force) option. After adding a file to the repo manually, you should rerun **vcsh write-gitignore** command. You need to decide in which git repo you want to store the generated *~/.gitignore.d/repo_name* file. You can choose the repo the file was generated for. Or maybe you want to store all *~/.gitignore.d/* files in a separate repo? **TODO**: automate the workflow related to the maintenance of *~/.gitignore.d/* files. --- ### vcsh-modules https://github.com/lierdakil/vcsh-modules/wiki vcsh-modules is intended for improving support of **git submodules** in vcsh. To define git submodules in a repository, create a configuration file *.gitmodules.d/repo_name* in the repository. The configuration file should specify git submodules. See example below: ``` [submodule ".config/awesome/vicious"] path = .config/awesome/vicious url = http://git.sysphere.org/vicious [submodule ".config/awesome/uzful"] path = .config/awesome/uzful url = https://github.com/dodo/uzful.git ``` ### Less known vcsh commands * list-tracked - List all files tracked by vcsh * which <substring> - Find substring in name of any tracked file # Prezto https://github.com/sorin-ionescu/prezto My fork: https://github.com/pawelkaczor/prezto Prezto is a configuration framework for Zsh. The Prezto git repository should be cloned to **~/.zprezto** directory. It contains **git submodules** that point to external git repositories hosting **Prezto modules**. --- * **Note** To update the Prezto modules run: ```git submodule update --init --recursive``` from ~/.zprezto directory. You should fork the Prezto and clone from the fork. Add **upstream** remote (eg. https://github.com/sorin-ionescu/prezto) to your local prezto git repository if you cloned from your fork, so you can merge changes from the upstream. For some reason I have not configured Prezto as a vcsh repository. Perhaps because of some issues with **git submodules**. **TODO**: update **vcsh-modules** and try to configure Prezto as a vcsh repository. --- \ No newline at end of file