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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*
 * Copyright (C) 2021  Aravinth Manivannan <realaravinth@batsense.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
//! Custom datastructure that controls mCaptcha lifetime through it's expiration event handler
//! and callbacks
use std::time::Duration;

use redis_module::key::RedisKeyWritable;
use redis_module::native_types::RedisType;
use redis_module::raw::KeyType;
use redis_module::{raw, Context};
use redis_module::{NotifyEvent, RedisString};
use serde::{Deserialize, Serialize};

use crate::bucket::Bucket;
use crate::errors::*;
use crate::mcaptcha::MCaptcha;
use crate::utils::*;

const MCAPTCHA_SAFETY_VERSION: i32 = 0;

#[derive(Serialize, Deserialize)]
pub struct MCaptchaSafety;

impl MCaptchaSafety {
    /// When safety is deleted due to expiration, if mcaptcha exists in cache a new safety should
    /// be created.
    pub fn on_delete(ctx: &Context, _event_type: NotifyEvent, _event: &str, key_name: &str) {
        if !is_mcaptcha_safety(key_name) {
            return;
        }

        let mcaptcha_name = get_mcaptcha_from_safety(key_name);
        if mcaptcha_name.is_none() {
            return;
        }
        let mcaptcha_name = mcaptcha_name.unwrap();
        let mcaptcha = ctx.open_key(&RedisString::create(ctx.ctx, mcaptcha_name));
        if mcaptcha.key_type() == KeyType::Empty {
            ctx.log_warning(&format!("mcaptcha {} is empty", mcaptcha_name));
            return;
        }

        let mcaptcha_val = MCaptcha::get_mcaptcha(&mcaptcha);
        if mcaptcha_val.is_err() {
            ctx.log_warning(&format!(
                "error occurred while trying to access mcaptcha {}. error {} is empty",
                mcaptcha_name,
                mcaptcha_val.err().unwrap()
            ));
            return;
        }
        let mcaptcha_val = mcaptcha_val.unwrap();
        if mcaptcha_val.is_none() {
            ctx.log_warning(&format!(
                "error occurred while trying to access mcaptcha {}. is none",
                mcaptcha_name,
            ));
            return;
        }
        let mcaptcha_val = mcaptcha_val.unwrap();
        let duration = mcaptcha_val.get_duration();
        let visitors = mcaptcha_val.get_visitors();

        if Self::new(ctx, duration, mcaptcha_name).is_err() {
            ctx.log_warning(&format!(
                "error occurred while creating safety for mcaptcha {}.",
                mcaptcha_name,
            ));
        };
        if visitors == 0 {
            ctx.log_warning(&format!(
                "visitors 0 for mcaptcha mcaptcha {}.",
                mcaptcha_name,
            ));
            return;
        }

        match Bucket::increment_by(ctx, (mcaptcha_name.to_owned(), duration), visitors) {
            Err(e) => ctx.log_warning(&format!("{}", e)),
            Ok(()) => ctx.log_debug(&format!(
                "Created new bucket making captcha {} eventually consistent",
                &mcaptcha_name
            )),
        }
    }

    #[allow(clippy::new_ret_no_self)]
    pub fn new(ctx: &Context, duration: u64, mcaptcha_name: &str) -> CacheResult<()> {
        let safety_name = get_safety_name(mcaptcha_name);
        let safety = ctx.open_key_writable(&RedisString::create(ctx.ctx, &safety_name));

        if safety.key_type() == KeyType::Empty {
            let safety_val = MCaptchaSafety {};
            safety.set_value(&MCAPTCHA_SAFETY_TYPE, safety_val)?;
            ctx.log_debug(&format!("mcaptcha safety created: {}", safety_name));
            Self::set_timer(ctx, &safety, (safety_name, duration))?;
        } else {
            ctx.log_debug(&format!("mcaptcha safety exists: {}", safety_name));
        }
        Ok(())
    }

    fn set_timer(
        ctx: &Context,
        safety: &RedisKeyWritable,
        (safety_name, duration): (String, u64),
    ) -> CacheResult<()> {
        let _ = ctx.create_timer(
            Duration::from_secs(duration),
            Self::boost,
            (safety_name, duration),
        );
        safety.set_expire(Duration::from_secs(duration * 2))?;
        Ok(())
    }

    /// executes when timer goes off. Refreshes expiry timer and resets timer
    fn boost(ctx: &Context, (safety_name, duration): (String, u64)) {
        let safety = ctx.open_key_writable(&RedisString::create(ctx.ctx, &safety_name));

        // if safety is available in cache then refresh timer
        if let Ok(Some(_safety_val)) = safety.get_value::<Self>(&MCAPTCHA_SAFETY_TYPE) {
            if let Err(e) = Self::set_timer(ctx, &safety, (safety_name, duration)) {
                // if unable to create timer, then safety will expire and mcaptcha will be deleted
                // as well. So when user requests pow config, there will be a cache miss, then
                // config will be loaded from db. This is fine.
                ctx.log_warning(&format!("{}", e))
            }
        // else create new safety
        } else {
            // see if mcaptcha exists before creating a safety for it.
            // Cases where mcaptcha doesn't exist or key is empty are ignored
            let mcaptcha_name = get_mcaptcha_from_safety(&safety_name);
            if mcaptcha_name.is_none() {
                return;
            }
            let mcaptcha_name = mcaptcha_name.unwrap();
            let mcaptcha = ctx.open_key(&RedisString::create(ctx.ctx, mcaptcha_name));
            if mcaptcha.key_type() == KeyType::Empty {
                return;
            }

            if let Ok(Some(_)) = MCaptcha::get_mcaptcha(&mcaptcha) {
                let res = Self::new(ctx, duration, mcaptcha_name);
                if res.is_err() {
                    ctx.log_warning(&format!(
                        "Error when creating safety timer for mcaptcha key: {}. Error: {}",
                        mcaptcha_name,
                        res.err().unwrap()
                    ));
                }
            }
        }
    }
}

pub static MCAPTCHA_SAFETY_TYPE: RedisType = RedisType::new(
    "mcaptsafe",
    MCAPTCHA_SAFETY_VERSION,
    raw::RedisModuleTypeMethods {
        version: raw::REDISMODULE_TYPE_METHOD_VERSION as u64,
        rdb_load: Some(type_methods::rdb_load),
        rdb_save: Some(type_methods::rdb_save),
        aof_rewrite: None,
        free: Some(type_methods::free),

        // Currently unused by Redis
        mem_usage: None,
        digest: None,

        // Aux data
        aux_load: None,
        aux_save: None,
        aux_save_triggers: 0,

        free_effort: None,
        unlink: None,
        copy: None,
        defrag: None,
    },
);

pub mod type_methods {
    use std::os::raw::c_void;

    use libc::c_int;

    const SAFETY_RDB_VAL: &str = "SAFETY";

    use super::*;
    #[allow(non_snake_case, unused)]
    pub extern "C" fn rdb_load(rdb: *mut raw::RedisModuleIO, encver: c_int) -> *mut c_void {
        let bucket = match encver {
            0 => {
                let data = raw::load_string(rdb).unwrap().to_string();
                if data == SAFETY_RDB_VAL {
                    MCaptchaSafety {}
                } else {
                    panic!("Can't safety from old redis RDB, data received : {}", data);
                }
            }
            _ => panic!(
                "Can't safety from old redis RDB, encoding version: {}",
                encver
            ),
        };

        //        if bucket.
        Box::into_raw(Box::new(bucket)) as *mut c_void
    }

    pub unsafe extern "C" fn free(value: *mut c_void) {
        let val = value as *mut MCaptchaSafety;
        Box::from_raw(val);
    }

    #[allow(non_snake_case, unused)]
    pub unsafe extern "C" fn rdb_save(rdb: *mut raw::RedisModuleIO, value: *mut c_void) {
        raw::save_string(rdb, SAFETY_RDB_VAL)
    }
}