Skip to content

Commit

Permalink
Ticket: Reduce locking overhead and eliminate some panic potential.
Browse files Browse the repository at this point in the history
Before: Lock. Maybe roll. Unlock. Lock. Do the work. Unlock.
After:  Lock. Maybe roll.               Do the work. Unlock.

This is still not ideal because the lock is held too long, and held over
inappropriate operations (syscalls). I will file a separate issue about
that. It was the case before this change as well.
  • Loading branch information
briansmith authored and pull[bot] committed Jan 16, 2023
1 parent 8327be0 commit 4231923
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions rustls/src/ticketer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::server::ProducesTickets;

use ring::aead;
use std::mem;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time;

/// The timebase for expiring and rolling tickets and ticketing
Expand Down Expand Up @@ -143,8 +143,10 @@ impl TicketSwitcher {
///
/// Calling this regularly will ensure timely key erasure. Otherwise,
/// key erasure will be delayed until the next encrypt/decrypt call.
fn maybe_roll(&self) -> Result<(), rand::GetRandomFailed> {
let mut state = self.state.lock().unwrap();
fn maybe_roll(
&self,
state: &mut MutexGuard<TicketSwitcherState>,
) -> Result<(), rand::GetRandomFailed> {
let now = timebase();

if now > state.next_switch_time {
Expand All @@ -165,20 +167,19 @@ impl ProducesTickets for TicketSwitcher {
}

fn encrypt(&self, message: &[u8]) -> Option<Vec<u8>> {
self.maybe_roll().ok()?;
let mut state = self.state.lock().ok()?;

self.state
.lock()
.unwrap()
.current
.encrypt(message)
self.maybe_roll(&mut state).ok()?;

state.current.encrypt(message)
}

fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> {
self.maybe_roll().ok()?;
let mut state = self.state.lock().ok()?;

self.maybe_roll(&mut state).ok()?;

// Decrypt with the current key; if that fails, try with the previous.
let state = self.state.lock().unwrap();
state
.current
.decrypt(ciphertext)
Expand Down

0 comments on commit 4231923

Please sign in to comment.