summaryrefslogtreecommitdiff
path: root/project2/cgi/cgiRequestID.cpp
blob: 6f4d01e209c39aee5e7434017637f257969d7a65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <pch.hpp>
#include <variables.h>
#include <scriptLoader.h>
#include <scriptStorage.h>
#include <appEngine.h>
#include <gcrypt.h>
#include <scopeObject.h>
#include <iomanip>

/// Variable implementation that returns a unique ID for a page request
class CgiRequestID : public VariableImplDyn {
	public:
		CgiRequestID(ScriptNodePtr e) :
			VariableImplDyn(e)
		{
		}

		VariableType value() const
		{
			gcry_md_hd_t state;
			gcry_md_open(&state, GCRY_MD_SHA1, 0);
			ScopeObject gcryClose([&state] { gcry_md_close(state); });

			auto _env = static_cast<const CgiEnvironment *>(ApplicationEngine::getCurrent()->env());
			gcryApplyString(state, _env->getRedirectURL());

			_env->applyAllParameters([&state,this](const std::string & name, const std::string & value) {
				gcryApplyString(state, name);
				gcryApplyString(state, value);
			});

			return hash(state);
		}

	private:
		static void gcryApplyString(gcry_md_hd_t & state, const std::string & str)
		{
			gcry_md_write(state, str.data(), str.length());
		}

		static std::string hash(gcry_md_hd_t & state)
		{
			int hash_len = gcry_md_get_algo_dlen(GCRY_MD_SHA1);
			unsigned char * hash = gcry_md_read(state, GCRY_MD_SHA1);
			std::stringstream hashstr;
			hashstr << std::hex << std::setfill('0');
			for (int i = 0; i < hash_len; i++) {
				hashstr << std::setw(2) << static_cast<unsigned>(hash[i]);
			}
			return hashstr.str();
		}
};
DECLARE_COMPONENT_LOADER("requestid", CgiRequestID, VariableLoader);