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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// client_persistence.rs
//
// This file is part of the Eclipse Paho MQTT Rust Client library.
//

/*******************************************************************************
 * Copyright (c) 2017-2018 Frank Pagliughi <fpagliughi@mindspring.com>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Frank Pagliughi - initial implementation and documentation
 *******************************************************************************/

use std::{
    ptr,
    slice,
    mem,
    ffi::{CString, CStr},
    os::raw::{c_void, c_char, c_int},
};
use libc;

use crate::{
    ffi,
    errors::Result,
};

// TODO: Should we have a specific PersistenceResult/Error?

pub const PERSISTENCE_SUCCESS: c_int = ffi::MQTTASYNC_SUCCESS as c_int;
pub const PERSISTENCE_ERROR: c_int = ffi::MQTTCLIENT_PERSISTENCE_ERROR;


/// Trait to implement custom persistence in the client.
pub trait ClientPersistence {
    /// Open and initialize the persistent store.
    /// `client_id` The unique client identifier.
    /// `server_uri` The address of the server to which the client is
    ///              connected.
    fn open(&mut self, client_id: &str, server_uri: &str) -> Result<()>;

    /// Close the persistence store.
    fn close(&mut self) -> Result<()>;

    /// Put data into the persistence store.
    /// `key` The key to the data.
    /// `buffers` The data to place into the store. Note that these can be
    ///           concatenated into a single, contiguous unit if helpful.
    fn put(&mut self, key: &str, buffers: Vec<&[u8]>) -> Result<()>;

    /// Gets data from the persistence store.
    /// `key` They key for the desired data.
    fn get(&mut self, key: &str) -> Result<Vec<u8>>;

    /// Removes data for the specified key.
    /// `key` The key for the data to remove.
    fn remove(&mut self, key: &str) -> Result<()>;

    /// Gets the keys that are currently in the persistence store
    fn keys(&mut self) -> Result<Vec<String>>;

    /// Clear the persistence store so that it no longer contains any data.
    fn clear(&mut self) -> Result<()>;

    /// Determines if the persistence store contains the key.
    /// `key` The key to look for.
    fn contains_key(&mut self, key: &str) -> bool;
}

/// The type for a client persistence object.
pub type ClientPersistenceType = Box<Box<dyn ClientPersistence + Send>>;

/////////////////////////////////////////////////////////////////////////////

/// A struct to wrap the user-defined client persistence objects for the
/// C library, including the callback funtions from the C library.
/// These functions receive the persistence callbacks from the C library and
/// then pass them on to the user-supplied struct which implements the
/// ClientPersistence trait.
///
/// Note that the C library _does not_ keep a copy of the
/// MQTTClient_persistence object, so the client must keep one and keep it
/// at a consistent address. Thus it should be kept in a box on the heap.
pub struct UserPersistence {
    /// The underlying struct for the C library
    pub(crate) copts: ffi::MQTTClient_persistence,
    /// The user-supplied persistence object
    _persistence: ClientPersistenceType,
}

impl UserPersistence
{
    /// Creates a new user persistence object.
    pub fn new(mut persistence: ClientPersistenceType) -> UserPersistence {
        let context = &mut *persistence as *mut Box<dyn ClientPersistence + Send> as _;

        UserPersistence {
            copts: ffi::MQTTClient_persistence {
                context,
                popen: Some(UserPersistence::on_open),
                pclose: Some(UserPersistence::on_close),
                pput: Some(UserPersistence::on_put),
                pget: Some(UserPersistence::on_get),
                premove: Some(UserPersistence::on_remove),
                pkeys: Some(UserPersistence::on_keys),
                pclear: Some(UserPersistence::on_clear),
                pcontainskey: Some(UserPersistence::on_contains_key),
            },
            _persistence: persistence,
        }
    }

    // Callback from the C library to open the persistence store.
    // On entry, the 'context' has the address of the user's persistence
    // object which is reassigned to the 'handle'.
    // Subsequent calls have the object address as the handle.
    pub unsafe extern "C" fn on_open(handle: *mut *mut c_void,
                                     client_id: *const c_char,
                                     server_uri: *const c_char,
                                     context: *mut c_void) -> c_int {
        trace!("UserPersistence::on_open");
        if !handle.is_null() && !client_id.is_null() && !server_uri.is_null() && !context.is_null() {
            let client_id = CStr::from_ptr(client_id).to_str().unwrap();
            let server_uri = CStr::from_ptr(server_uri).to_str().unwrap();

            let persist: &mut Box<dyn ClientPersistence> = mem::transmute(context);

            if let Ok(_) = persist.open(client_id, server_uri) {
                *handle = context;
                return PERSISTENCE_SUCCESS;
            }
        }
        PERSISTENCE_ERROR
    }

    /// Callback from the C library to close the persistence store.
    pub unsafe extern "C" fn on_close(handle: *mut c_void) -> c_int {
        trace!("UserPersistence::on_close");
        if handle.is_null() {
            return PERSISTENCE_ERROR;
        }

        let persist: &mut Box<dyn ClientPersistence> = mem::transmute(handle);

        match persist.close() {
            Ok(_) => PERSISTENCE_SUCCESS,
            Err(_) => PERSISTENCE_ERROR,
        }
    }

    /// Callback from the C library to add data to the persistence store
    pub unsafe extern "C" fn on_put(handle: *mut c_void,
                                    key: *mut c_char,
                                    bufcount: c_int,
                                    buffers: *mut *mut c_char,
                                    buflens: *mut c_int) -> c_int {
        trace!("UserPersistence::on_put");
        if handle.is_null() || key.is_null() ||
                buffers.is_null() || buflens.is_null() {
            return PERSISTENCE_ERROR;
        }
        if bufcount == 0 {
            return PERSISTENCE_SUCCESS;
        }
        let persist: &mut Box<dyn ClientPersistence> = mem::transmute(handle);
        let key = CStr::from_ptr(key).to_str().unwrap();

        let mut bufs: Vec<&[u8]> = Vec::new();

        for i in 0..bufcount as isize {
            let buf = slice::from_raw_parts_mut(*buffers.offset(i) as *mut u8,
                                                *buflens.offset(i) as usize);
            bufs.push(buf);
        }
        match persist.put(key, bufs) {
            Ok(_)  => PERSISTENCE_SUCCESS,
            Err(_) => PERSISTENCE_ERROR,
        }
    }

    /// Callback from the C library to retrieve data from the
    /// persistence store.
    pub unsafe extern "C" fn on_get(handle: *mut c_void,
                                    key: *mut c_char,
                                    buffer: *mut *mut c_char,
                                    buflen: *mut c_int) -> c_int {
        trace!("UserPersistence::on_get");
        if handle.is_null() || key.is_null() ||
                buffer.is_null() || buflen.is_null() {
            return PERSISTENCE_ERROR;
        }
        let persist: &mut Box<dyn ClientPersistence> = mem::transmute(handle);
        let key = CStr::from_ptr(key).to_str().unwrap();

        match persist.get(key) {
            Ok(buf) => {    // buf: Vec<u8>
                let n = buf.len();
                let cbuf = libc::malloc(n) as *mut u8;
                ptr::copy(buf.as_ptr(), cbuf, n);
                *buffer = cbuf as *mut c_char;
                *buflen = n as c_int;
                PERSISTENCE_SUCCESS
            },
            Err(_) => PERSISTENCE_ERROR,
        }
    }

    /// Callback from the C library to delete specific data from the
    /// persistence store.
    pub unsafe extern "C" fn on_remove(handle: *mut c_void,
                                       key: *mut c_char) -> c_int {
        trace!("UserPersistence::on_remove");
        if handle.is_null() || key.is_null() {
            return PERSISTENCE_ERROR;
        }
        let persist: &mut Box<dyn ClientPersistence> = mem::transmute(handle);
        let key = CStr::from_ptr(key).to_str().unwrap();

        match persist.remove(key) {
            Ok(_) => PERSISTENCE_SUCCESS,
            Err(_) => PERSISTENCE_ERROR
        }
    }

    /// Callback from the C library to retrieve the set of keys from the
    /// persistence store.
    pub unsafe extern "C" fn on_keys(handle: *mut c_void,
                                     keys: *mut *mut *mut c_char,
                                     nkeys: *mut c_int) -> c_int {
        trace!("UserPersistence::on_keys");
        if handle.is_null() || keys.is_null() || nkeys.is_null() {
            return PERSISTENCE_ERROR;
        }

        let persist: &mut Box<dyn ClientPersistence> = mem::transmute(handle);

        *keys = ptr::null_mut();
        *nkeys = 0;

        match persist.keys() {
            Ok(k) => {      // k: Vec<String>
                let n = k.len();
                if n != 0 {
                    // TODO OPTIMIZE: This does a lot of copying
                    let ckeys = libc::malloc(n * mem::size_of::<usize>()) as *mut *mut c_char;
                    for i in 0..n {
                        let s = CString::new(k[i].clone()).unwrap();
                        let sb = s.as_bytes_with_nul();
                        let sn = sb.len();
                        let cbuf = libc::malloc(sn) as *mut c_char;
                        ptr::copy(sb.as_ptr(), cbuf as *mut u8, sn);

                        *ckeys.offset(i as isize) = cbuf;
                    }
                    *keys = ckeys;
                    *nkeys = n as c_int;
                }
                PERSISTENCE_SUCCESS
            },
            Err(_) => PERSISTENCE_ERROR
        }
    }

    /// Callback from the C library to remove all the data from the
    /// persistence store.
    pub unsafe extern "C" fn on_clear(handle: *mut c_void) -> c_int {
        trace!("UserPersistence::on_clear");
        if handle.is_null() {
            return PERSISTENCE_ERROR;
        }
        let persist: &mut Box<dyn ClientPersistence> = mem::transmute(handle);

        match persist.clear() {
            Ok(_) => PERSISTENCE_SUCCESS,
            Err(_) => PERSISTENCE_ERROR,
        }
    }

    /// Callback from the C library to determine if the store contains
    /// the specified key.
    pub unsafe extern "C" fn on_contains_key(handle: *mut c_void,
                                             key: *mut c_char) -> c_int {
        trace!("UserPersistence::on_contains_key");
        if handle.is_null() || key.is_null() {
            return PERSISTENCE_ERROR;
        }
        let persist: &mut Box<dyn ClientPersistence> = mem::transmute(handle);
        let key = CStr::from_ptr(key).to_str().unwrap();

        if persist.contains_key(key) { 1 } else { 0 }
    }
}

/////////////////////////////////////////////////////////////////////////////
//                              Unit Tests
/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    /*
    use super::*;
    //use std::ffi::{CStr};

    struct TestClientPersistence;

    impl ClientPersistence for TestClientPersistence {
        fn open(&self, client_id: &str, server_uri: &str) -> Result<()> {
            Ok(())
        }

        fn close(&self) -> Result<()> {
            Ok(())
        }

        fn clear(&self) -> Result<()> {
            Ok(())
        }

        fn put(&self, key: &str, buffers: Vec<&[u8]>) -> Result<()> {
            Ok(())
        }

        fn get(&self, key: &str) -> Result<&[u8]> {
            let x = b"Bubba";   //: &'static [u8] = &'static [ 0u8, 1u8, 2u8, 3u8 ];
            Ok(x)
        }

        fn remove(&self, key: &str) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn test_new() {
        let tcp = TestClientPersistence {};
        let tcpp = Box::new(Box::new(tcp));
        let context = Box::into_raw(tcpp);

        let persist: &mut Box<ClientPersistence> = unsafe { mem::transmute(context) };
        /*
        let persist: &mut Box<ClientPersistence> = unsafe { mem::transmute(context) };
        let res = persist.open("clientid", "tcp://localhost:1883");
        assert!(res.is_ok());
        */

        let _ = unsafe { Box::from_raw(context) };
    }
    */
}