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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! The Pact `Message` type, including associated matching rules and provider states.

/*===============================================================================================
 * # Imports
 *---------------------------------------------------------------------------------------------*/

use crate::models::pact_specification::PactSpecification;
use crate::util::*;
use crate::{as_mut, as_ref, cstr, ffi_fn, safe_str};
use anyhow::{anyhow, Context};
use libc::{c_char, c_int, c_uint, EXIT_FAILURE, EXIT_SUCCESS};
use pact_models::{content_types::ContentType};
use pact_models::bodies::OptionalBody;
use serde_json::from_str as from_json_str;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::ops::Drop;

/*===============================================================================================
 * # Re-Exports
 *---------------------------------------------------------------------------------------------*/

// Necessary to make 'cbindgen' generate an opaque struct on the C side.
pub use pact_models::message::Message;
pub use pact_models::provider_states::ProviderState;

/*===============================================================================================
 * # Message
 *---------------------------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------------------------
 * ## Constructors / Destructor
 */

ffi_fn! {
    /// Get a mutable pointer to a newly-created default message on the heap.
    ///
    /// # Safety
    ///
    /// This function is safe.
    ///
    /// # Error Handling
    ///
    /// Returns NULL on error.
    fn pactffi_message_new() -> *mut Message {
        let message = Message::default();
        ptr::raw_to(message)
    } {
        ptr::null_mut_to::<Message>()
    }
}

ffi_fn! {
    /// Constructs a `Message` from the JSON string
    ///
    /// # Safety
    ///
    /// This function is safe.
    ///
    /// # Error Handling
    ///
    /// If the JSON string is invalid or not UTF-8 encoded, returns a NULL.
    fn pactffi_message_new_from_json(
        index: c_uint,
        json_str: *const c_char,
        spec_version: PactSpecification
    ) -> *mut Message {
        let message = {
            let index = index as usize;
            let json_value: JsonValue = from_json_str(safe_str!(json_str))
                .context("error parsing json_str as JSON")?;
            let spec_version = spec_version.into();

            Message::from_json(index, &json_value, &spec_version)
                .map_err(|e| anyhow::anyhow!("{}", e))?
        };

        ptr::raw_to(message)
    } {
        ptr::null_mut_to::<Message>()
    }
}

ffi_fn! {
    /// Constructs a `Message` from a body with a given content-type.
    ///
    /// # Safety
    ///
    /// This function is safe.
    ///
    /// # Error Handling
    ///
    /// If the body or content type are invalid or not UTF-8 encoded, returns NULL.
    fn pactffi_message_new_from_body(body: *const c_char, content_type: *const c_char) -> *mut Message {
        // Get the body as a Vec<u8>.
        let body = cstr!(body)
            .to_bytes()
            .to_owned();

        // Parse the content type.
        let content_type = ContentType::parse(safe_str!(content_type))
            .map_err(|s| anyhow!("invalid content type '{}'", s))?;

        // Populate the Message metadata.
        let mut metadata = HashMap::new();
        metadata.insert(String::from("contentType"), JsonValue::String(content_type.to_string()));

        // Populate the OptionalBody with our content and content type.
        let contents = OptionalBody::Present(body.into(), Some(content_type), None);

        // Construct and return the message.
        let message = Message {
            contents,
            metadata,
            .. Message::default()
        };

        ptr::raw_to(message)
    } {
        ptr::null_mut_to::<Message>()
    }
}

ffi_fn! {
    /// Destroy the `Message` being pointed to.
    fn pactffi_message_delete(message: *mut Message) {
        ptr::drop_raw(message);
    }
}

/*-----------------------------------------------------------------------------------------------
 * ## Contents
 */

ffi_fn! {
    /// Get the contents of a `Message`.
    ///
    /// # Safety
    ///
    /// The returned string must be deleted with `pactffi_string_delete`.
    ///
    /// The returned string can outlive the message.
    ///
    /// # Error Handling
    ///
    /// If the message is NULL, returns NULL. If the body of the message
    /// is missing, then this function also returns NULL. This means there's
    /// no mechanism to differentiate with this function call alone between
    /// a NULL message and a missing message body.
    fn pactffi_message_get_contents(message: *const Message) -> *const c_char {
        let message = as_ref!(message);

        match message.contents {
            // If it's missing, return a null pointer.
            OptionalBody::Missing => ptr::null_to::<c_char>(),
            // If empty or null, return an empty string on the heap.
            OptionalBody::Empty | OptionalBody::Null => {
                let content = string::to_c("")?;
                content as *const c_char
            }
            // Otherwise, get the contents, possibly still empty.
            _ => {
                let content = string::to_c(message.contents.str_value())?;
                content as *const c_char
            }
        }
    } {
        ptr::null_to::<c_char>()
    }
}

/*-----------------------------------------------------------------------------------------------
 * ## Description
 */

ffi_fn! {
    /// Get a copy of the description.
    ///
    /// # Safety
    ///
    /// The returned string must be deleted with `pactffi_string_delete`.
    ///
    /// Since it is a copy, the returned string may safely outlive
    /// the `Message`.
    ///
    /// # Errors
    ///
    /// On failure, this function will return a NULL pointer.
    ///
    /// This function may fail if the Rust string contains embedded
    /// null ('\0') bytes.
    fn pactffi_message_get_description(message: *const Message) -> *const c_char {
        let message = as_ref!(message);
        let description = string::to_c(&message.description)?;
        description as *const c_char
    } {
        ptr::null_to::<c_char>()
    }
}

ffi_fn! {
    /// Write the `description` field on the `Message`.
    ///
    /// # Safety
    ///
    /// `description` must contain valid UTF-8. Invalid UTF-8
    /// will be replaced with U+FFFD REPLACEMENT CHARACTER.
    ///
    /// This function will only reallocate if the new string
    /// does not fit in the existing buffer.
    ///
    /// # Error Handling
    ///
    /// Errors will be reported with a non-zero return value.
    fn pactffi_message_set_description(message: *mut Message, description: *const c_char) -> c_int {
        let message = as_mut!(message);
        let description = safe_str!(description);

        // Wipe out the previous contents of the string, without
        // deallocating, and set the new description.
        message.description.clear();
        message.description.push_str(description);

        EXIT_SUCCESS
    } {
        EXIT_FAILURE
    }
}

/*-----------------------------------------------------------------------------------------------
 * ## Provider States
 */

ffi_fn! {
    /// Get a copy of the provider state at the given index from this message.
    ///
    /// # Safety
    ///
    /// The returned structure must be deleted with `provider_state_delete`.
    ///
    /// Since it is a copy, the returned structure may safely outlive
    /// the `Message`.
    ///
    /// # Error Handling
    ///
    /// On failure, this function will return a variant other than Success.
    ///
    /// This function may fail if the index requested is out of bounds,
    /// or if any of the Rust strings contain embedded null ('\0') bytes.
    fn pactffi_message_get_provider_state(message: *const Message, index: c_uint) -> *const ProviderState {
        let message = as_ref!(message);
        let index = index as usize;

        // Get a raw pointer directly, rather than boxing it, as its owned by the `Message`
        // and will be cleaned up when the `Message` is cleaned up.
        let provider_state = message
            .provider_states
            .get(index)
            .ok_or(anyhow!("index is out of bounds"))?;

        provider_state as *const ProviderState
    } {
        ptr::null_to::<ProviderState>()
    }
}

ffi_fn! {
    /// Get an iterator over provider states.
    ///
    /// # Safety
    ///
    /// The underlying data must not change during iteration.
    ///
    /// # Error Handling
    ///
    /// Returns NULL if an error occurs.
    fn pactffi_message_get_provider_state_iter(message: *mut Message) -> *mut ProviderStateIterator {
        let message = as_mut!(message);
        let iter = ProviderStateIterator { current: 0, message };
        ptr::raw_to(iter)
    } {
        ptr::null_mut_to::<ProviderStateIterator>()
    }
}

ffi_fn! {
    /// Get the next value from the iterator.
    ///
    /// # Safety
    ///
    /// The underlying data must not change during iteration.
    ///
    /// # Error Handling
    ///
    /// Returns NULL if an error occurs.
    fn pactffi_provider_state_iter_next(iter: *mut ProviderStateIterator) -> *mut ProviderState {
        let iter = as_mut!(iter);
        let message = as_mut!(iter.message);
        let index = iter.next();
        let provider_state = message
            .provider_states
            .get_mut(index)
            .ok_or(anyhow::anyhow!("iter past the end of provider states"))?;
       provider_state as *mut ProviderState
    } {
        ptr::null_mut_to::<ProviderState>()
    }
}

ffi_fn! {
    /// Delete the iterator.
    fn pactffi_provider_state_iter_delete(iter: *mut ProviderStateIterator) {
        ptr::drop_raw(iter);
    }
}

/// Iterator over individual provider states.
#[allow(missing_copy_implementations)]
#[allow(missing_debug_implementations)]
pub struct ProviderStateIterator {
    current: usize,
    message: *mut Message,
}

impl ProviderStateIterator {
    fn next(&mut self) -> usize {
        let idx = self.current;
        self.current += 1;
        idx
    }
}

/*-----------------------------------------------------------------------------------------------
 * ## Metadata
 */

ffi_fn! {
    /// Get a copy of the metadata value indexed by `key`.
    ///
    /// # Safety
    ///
    /// The returned string must be deleted with `pactffi_string_delete`.
    ///
    /// Since it is a copy, the returned string may safely outlive
    /// the `Message`.
    ///
    /// The returned pointer will be NULL if the metadata does not contain
    /// the given key, or if an error occurred.
    ///
    /// # Error Handling
    ///
    /// On failure, this function will return a NULL pointer.
    ///
    /// This function may fail if the provided `key` string contains
    /// invalid UTF-8, or if the Rust string contains embedded null ('\0')
    /// bytes.
    fn pactffi_message_find_metadata(message: *const Message, key: *const c_char) -> *const c_char {
        let message = as_ref!(message);
        let key = safe_str!(key);
        let value = message.metadata.get(key).ok_or(anyhow::anyhow!("invalid metadata key"))?;
        let value_ptr = string::to_c(value.as_str().unwrap_or_default())?;
        value_ptr as *const c_char
    } {
        ptr::null_to::<c_char>()
    }
}

ffi_fn! {
    /// Insert the (`key`, `value`) pair into this Message's
    /// `metadata` HashMap.
    ///
    /// # Safety
    ///
    /// This function returns an enum indicating the result;
    /// see the comments on HashMapInsertStatus for details.
    ///
    /// # Error Handling
    ///
    /// This function may fail if the provided `key` or `value` strings
    /// contain invalid UTF-8.
    fn pactffi_message_insert_metadata(
        message: *mut Message,
        key: *const c_char,
        value: *const c_char
    ) -> c_int {
        let message = as_mut!(message);
        let key = safe_str!(key);
        let value = safe_str!(value);

        match message.metadata.insert(key.to_string(), JsonValue::String(value.to_string())) {
            None => HashMapInsertStatus::SuccessNew as c_int,
            Some(_) => HashMapInsertStatus::SuccessOverwrite as c_int,
        }
    } {
        HashMapInsertStatus::Error as c_int
    }
}

ffi_fn! {
    /// Get an iterator over the metadata of a message.
    ///
    /// # Safety
    ///
    /// This iterator carries a pointer to the message, and must
    /// not outlive the message.
    ///
    /// The message metadata also must not be modified during iteration. If it is,
    /// the old iterator must be deleted and a new iterator created.
    ///
    /// # Error Handling
    ///
    /// On failure, this function will return a NULL pointer.
    ///
    /// This function may fail if any of the Rust strings contain
    /// embedded null ('\0') bytes.
    fn pactffi_message_get_metadata_iter(message: *mut Message) -> *mut MessageMetadataIterator {
        let message = as_mut!(message);

        let iter = MessageMetadataIterator {
            keys:  message.metadata.keys().cloned().collect(),
            current: 0,
            message: message as *const Message,
        };

        ptr::raw_to(iter)
    } {
        ptr::null_mut_to::<MessageMetadataIterator>()
    }
}

ffi_fn! {
    /// Get the next key and value out of the iterator, if possible
    ///
    /// # Safety
    ///
    /// The underlying data must not change during iteration.
    ///
    /// # Error Handling
    ///
    /// If no further data is present, returns NULL.
    fn pactffi_message_metadata_iter_next(iter: *mut MessageMetadataIterator) -> *mut MessageMetadataPair {
        let iter = as_mut!(iter);
        let message = as_ref!(iter.message);
        let key = iter.next().ok_or(anyhow::anyhow!("iter past the end of metadata"))?;
        let (key, value) = message
            .metadata
            .get_key_value(key)
            .ok_or(anyhow::anyhow!("iter provided invalid metadata key"))?;
        let pair = MessageMetadataPair::new(key, value.as_str().unwrap_or_default())?;
        ptr::raw_to(pair)
    } {
        ptr::null_mut_to::<MessageMetadataPair>()
    }
}

ffi_fn! {
    /// Free the metadata iterator when you're done using it.
    fn pactffi_message_metadata_iter_delete(iter: *mut MessageMetadataIterator) {
        ptr::drop_raw(iter);
    }
}

ffi_fn! {
    /// Free a pair of key and value returned from `message_metadata_iter_next`.
    fn pactffi_message_metadata_pair_delete(pair: *mut MessageMetadataPair) {
        ptr::drop_raw(pair);
    }
}

/// An iterator that enables FFI iteration over metadata by putting all the keys on the heap
/// and tracking which one we're currently at.
///
/// This assumes no mutation of the underlying metadata happens while the iterator is live.
#[derive(Debug)]
pub struct MessageMetadataIterator {
    /// The metadata keys
    keys: Vec<String>,
    /// The current key
    current: usize,
    /// Pointer to the message.
    message: *const Message,
}

impl MessageMetadataIterator {
    fn next(&mut self) -> Option<&String> {
        let idx = self.current;
        self.current += 1;
        self.keys.get(idx)
    }
}

/// A single key-value pair exported to the C-side.
#[derive(Debug)]
#[repr(C)]
#[allow(missing_copy_implementations)]
pub struct MessageMetadataPair {
    /// The metadata key.
    key: *const c_char,
    /// The metadata value.
    value: *const c_char,
}

impl MessageMetadataPair {
    fn new(
        key: &str,
        value: &str,
    ) -> anyhow::Result<MessageMetadataPair> {
        Ok(MessageMetadataPair {
            key: string::to_c(key)? as *const c_char,
            value: string::to_c(value)? as *const c_char,
        })
    }
}

// Ensure that the owned strings are freed when the pair is dropped.
//
// Notice that we're casting from a `*const c_char` to a `*mut c_char`.
// This may seem wrong, but is safe so long as it doesn't violate Rust's
// guarantees around immutable references, which this doesn't. In this case,
// the underlying data came from `CString::into_raw` which takes ownership
// of the `CString` and hands it off via a `*mut pointer`. We cast that pointer
// back to `*const` to limit the C-side from doing any shenanigans, since the
// pointed-to values live inside of the `Message` metadata `HashMap`, but
// cast back to `*mut` here so we can free the memory.
//
// The discussion here helps explain: https://github.com/rust-lang/rust-clippy/issues/4774
impl Drop for MessageMetadataPair {
    fn drop(&mut self) {
        string::pactffi_string_delete(self.key as *mut c_char);
        string::pactffi_string_delete(self.value as *mut c_char);
    }
}

/*===============================================================================================
 * # Status Types
 *---------------------------------------------------------------------------------------------*/

/// Result from an attempt to insert into a HashMap
enum HashMapInsertStatus {
    /// The value was inserted, and the key was unset
    SuccessNew = 0,
    /// The value was inserted, and the key was previously set
    SuccessOverwrite = -1,
    /// An error occured, and the value was not inserted
    Error = -2,
}