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
pub mod prefix;

use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf, time::Duration};

use nix::unistd::{chown, Gid, Uid};
use simple_pretty::halt;
use serde::{Deserialize, Serialize};
use dusa_collection_utils::{
    errors::{
        ErrorArray, ErrorArrayItem, Errors as SE, OkWarning, UnifiedResult as uf, WarningArray,
        WarningArrayItem, Warnings,
    },
    functions::del_file,
    types::PathType,
};
use users::{Groups, Users, UsersCache};

/// Current version of the protocol, derived from the package version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Time to live in seconds for file that are decrypted.
pub const TTL: u64 = 30;

/// Getting the current uid
pub fn get_id() -> (Uid, Gid) {
    let user_cache: UsersCache = UsersCache::new();
    let dusa_uid = user_cache.get_user_by_name("dusa").unwrap().uid();
    let dusa_gid = user_cache.get_group_by_name("dusa").unwrap().gid();

    (Uid::from_raw(dusa_uid), Gid::from_raw(dusa_gid))
}

/// Struct representing a write request.
#[derive(Serialize, Deserialize, Debug)]
pub struct RequestRecsWrite {
    pub path: PathType,
    pub owner: String,
    pub name: String,
    pub uid: u32,
}

/// Struct representing a plain text request.
#[derive(Serialize, Deserialize, Debug)]
pub struct RequestRecsPlainText {
    pub command: Commands,
    pub data: String,
    pub uid: u32,
}

/// Struct representing a simple request.
#[derive(Serialize, Deserialize, Debug)]
pub struct RequestRecsSimple {
    pub command: Commands,
    pub owner: String,
    pub name: String,
    pub uid: u32,
}

/// Struct representing a response.
#[derive(Serialize, Deserialize, Debug)]
pub struct ResponseData {
    pub status: String,
    pub detail: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DecryptResponseData{
    pub temp_p: PathType,
    pub orig_p: PathType,
    pub ttl: Duration,
}

/// Enum representing different request payloads.
#[derive(Serialize, Deserialize, Debug)]
pub enum RequestPayload {
    Write(RequestRecsWrite),
    PlainText(RequestRecsPlainText),
    Simple(RequestRecsSimple),
}

/// enums for commands 
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum Commands {
    EncryptRawText,
    DecryptRawText,
    DecryptFile,
    RemoveFile,
    PingFile,
}

/// Generic message struct used for communication.
#[derive(Serialize, Deserialize, Debug)]
pub struct Message<T> {
    pub version: String,
    pub msg_type: MessageType,
    pub payload: T,
    pub error: Option<DusaError>,
}

/// Enum representing different message types.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum MessageType {
    Request,
    Response,
    ErrorResponse,
    Simple,
    Acknowledge,
    Test,
    // Add more custom message types as needed
}

/// Enum representing different error codes.
#[derive(Serialize, Deserialize, Debug)]
pub enum ErrorCode {
    UnknownMessageType,
    InvalidPayload,
    InvalidVersion,
    InternalError,
    InvalidPermissions,
    // Add more standardized error codes as needed
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ErrorCode::UnknownMessageType => write!(f, "Unknown message type"),
            ErrorCode::InvalidPayload => write!(f, "Invalid payload"),
            ErrorCode::InternalError => write!(f, "Internal error"),
            ErrorCode::InvalidVersion => write!(f, "We aren't speaking the same language"),
            ErrorCode::InvalidPermissions => write!(f, "You have no authority here"),
            // Add more standardized error codes as needed
        }
    }
}

impl std::fmt::Display for Commands {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Commands::EncryptRawText => write!(f, "et"),
            Commands::DecryptRawText => write!(f, "dt"),
            Commands::DecryptFile => write!(f, "df"),
            Commands::RemoveFile => write!(f, "rf"),
            Commands::PingFile => write!(f, "pf"),
        }
    }
}

/// Struct representing an error message.
#[derive(Serialize, Deserialize, Debug)]
pub struct DusaError {
    pub code: ErrorCode,
    pub message: String,
}

pub fn check_version(incoming_version: &str) -> bool {
    // Split the version strings into major, minor, and patch parts
    let parse_version = |v: &str| -> Option<(u32, u32)> {
        let parts: Vec<&str> = v.split('.').collect();
        if parts.len() != 3 {
            return None;
        }
        let major = parts[0].parse::<u32>().ok()?;
        let minor = parts[1].parse::<u32>().ok()?;
        let _patch: u32 = parts[2].parse::<u32>().ok()?;
        Some((major, minor))
    };

    if let (Some((inc_major, inc_minor)), Some((ver_major, ver_minor))) =
        (parse_version(incoming_version), parse_version(VERSION))
    {
        inc_major == ver_major && inc_minor == ver_minor
    } else {
        false
    }
}


/// Returns the path to the socket.
///
/// # Arguments
/// * `int` - A boolean indicating if initialization is needed.
/// * `errors` - An array of errors to be populated if any occur.
/// * `warnings` - An array of warnings to be populated if any occur.
///
/// # Returns
/// A unified result containing the path type or errors/warnings.
#[allow(nonstandard_style)]
pub fn SOCKET_PATH(
    int: bool,
    mut errors: ErrorArray,
    mut warnings: WarningArray,
) -> uf<OkWarning<PathType>> {
    let socket_file = PathType::Content(String::from("/var/run/dusa/dusa.sock"));
    // let socket_file = PathType::Content(String::from("/home/dwhitfield/Developer/RUST/Dev/server/s.socket"));
    let _socket_dir = match socket_file.ancestors().next() {
        Some(d) => PathType::PathBuf(d.to_path_buf()),
        None => {
            errors.push(ErrorArrayItem::new(
                SE::InvalidFile,
                "Socket file not found".to_string(),
            ));
            return uf::new(Err(errors));
        }
    };

    if int {
        // Create the dir and the sock file
        if socket_file.exists() {
            match del_file(socket_file.clone(), errors.clone(), warnings.clone()).uf_unwrap() {
                Ok(_) => {
                    return uf::new(Ok(OkWarning {
                        data: socket_file,
                        warning: warnings,
                    }));
                }
                Err(_) => {
                    warnings.push(WarningArrayItem::new(Warnings::OutdatedVersion));
                }
            }
        }
    }

    uf::new(Ok(OkWarning {
        data: socket_file,
        warning: warnings,
    }))
}

pub fn set_file_ownership(path: &PathBuf, uid: Uid, gid: Gid, mut errors: ErrorArray) -> uf<()> {
    match chown(path, Some(uid), Some(gid)) {
        Ok(_) => uf::new(Ok(())),
        Err(_) => {
            errors.push(ErrorArrayItem::new(
                dusa_collection_utils::errors::Errors::Unauthorized,
                String::from("chown failed"),
            ));
            uf::new(Err(errors))
        }
    }
}

pub fn set_socket_permission(socket_path: PathType) {
    // Changing the permissions the socket
    let socket_metadata = match fs::metadata(socket_path.clone()) {
        Ok(d) => d,
        Err(e) => {
            halt(&format!(
                "Couldn't read meta data of the socket: {}",
                &e.to_string()
            ));
            unreachable!()
        }
    };
    let mut permissions = socket_metadata.permissions();
    permissions.set_mode(0o660); // Set desired permissions

    match fs::set_permissions(socket_path.clone(), permissions) {
        Ok(()) => (),
        Err(e) => halt(&format!(
            "We own the socket but we can't change its permissions, all i know is '{}'",
            &e.to_string()
        )),
    };
}

impl std::fmt::Display for MessageType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MessageType::Request => write!(f, "Request"),
            MessageType::Response => write!(f, "Response"),
            MessageType::ErrorResponse => write!(f, "Error"),
            MessageType::Simple => write!(f, "Simple Message"),
            MessageType::Acknowledge => write!(f, "Understood"),
            MessageType::Test => write!(f, "Test message"),
            // Add more custom message types as needed
        }
    }
}