summaryrefslogtreecommitdiff
path: root/project2/cgi/cgiRequestID.cpp
blob: 038fff51e8ca63269bc8cb0513c9db98df52b0c0 (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 "cgiRequestContext.h"
#include <scriptLoader.h>
#include <scriptStorage.h>
#include <gcrypt.h>
#include <scopeExit.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(ExecContext * ec) const
		{
			gcry_md_hd_t state;
			gcry_md_open(&state, GCRY_MD_SHA1, 0);
			AdHoc::ScopeExit gcryClose([&state] { gcry_md_close(state); });

			auto crc = static_cast<const CgiRequestContext *>(ec);
			gcryApplyString(state, crc->getRedirectURL());

			crc->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);