mysqladm/cli/mysql_admutils_compatibility/
mysql_useradm.rs

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
use clap::Parser;
use futures_util::{SinkExt, StreamExt};
use std::path::PathBuf;

use std::os::unix::net::UnixStream as StdUnixStream;
use tokio::net::UnixStream as TokioUnixStream;

use crate::{
    cli::{
        common::erroneous_server_response,
        mysql_admutils_compatibility::{
            common::trim_user_name_to_32_chars,
            error_messages::{
                handle_create_user_error, handle_drop_user_error, handle_list_users_error,
            },
        },
        user_command::read_password_from_stdin_with_double_check,
    },
    core::{
        bootstrap::bootstrap_server_connection_and_drop_privileges,
        protocol::{
            create_client_to_server_message_stream, ClientToServerMessageStream, MySQLUser,
            Request, Response,
        },
    },
    server::sql::user_operations::DatabaseUser,
};

/// Create, delete or change password for the USER(s),
/// as determined by the COMMAND.
///
/// This is a compatibility layer for the mysql-useradm command.
/// Please consider using the newer mysqladm command instead.
#[derive(Parser)]
#[command(
    bin_name = "mysql-useradm",
    version,
    about,
    disable_help_subcommand = true,
    verbatim_doc_comment
)]
pub struct Args {
    #[command(subcommand)]
    pub command: Option<Command>,

    /// Path to the socket of the server, if it already exists.
    #[arg(
        short,
        long,
        value_name = "PATH",
        global = true,
        hide_short_help = true
    )]
    server_socket_path: Option<PathBuf>,

    /// Config file to use for the server.
    #[arg(
        short,
        long,
        value_name = "PATH",
        global = true,
        hide_short_help = true
    )]
    config: Option<PathBuf>,
}

#[derive(Parser)]
pub enum Command {
    /// create the USER(s).
    Create(CreateArgs),

    /// delete the USER(s).
    Delete(DeleteArgs),

    /// change the MySQL password for the USER(s).
    Passwd(PasswdArgs),

    /// give information about the USERS(s), or, if
    /// none are given, all the users you have.
    Show(ShowArgs),
}

#[derive(Parser)]
pub struct CreateArgs {
    /// The name of the USER(s) to create.
    #[arg(num_args = 1..)]
    name: Vec<MySQLUser>,
}

#[derive(Parser)]
pub struct DeleteArgs {
    /// The name of the USER(s) to delete.
    #[arg(num_args = 1..)]
    name: Vec<MySQLUser>,
}

#[derive(Parser)]
pub struct PasswdArgs {
    /// The name of the USER(s) to change the password for.
    #[arg(num_args = 1..)]
    name: Vec<MySQLUser>,
}

#[derive(Parser)]
pub struct ShowArgs {
    /// The name of the USER(s) to show.
    #[arg(num_args = 0..)]
    name: Vec<MySQLUser>,
}

pub fn main() -> anyhow::Result<()> {
    let args: Args = Args::parse();

    let command = match args.command {
        Some(command) => command,
        None => {
            println!(
                "Try `{} --help' for more information.",
                std::env::args()
                    .next()
                    .unwrap_or("mysql-useradm".to_string())
            );
            return Ok(());
        }
    };

    let server_connection =
        bootstrap_server_connection_and_drop_privileges(args.server_socket_path, args.config)?;

    tokio_run_command(command, server_connection)?;

    Ok(())
}

fn tokio_run_command(command: Command, server_connection: StdUnixStream) -> anyhow::Result<()> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            let tokio_socket = TokioUnixStream::from_std(server_connection)?;
            let message_stream = create_client_to_server_message_stream(tokio_socket);
            match command {
                Command::Create(args) => create_user(args, message_stream).await,
                Command::Delete(args) => drop_users(args, message_stream).await,
                Command::Passwd(args) => passwd_users(args, message_stream).await,
                Command::Show(args) => show_users(args, message_stream).await,
            }
        })
}

async fn create_user(
    args: CreateArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    let db_users = args.name.iter().map(trim_user_name_to_32_chars).collect();

    let message = Request::CreateUsers(db_users);
    server_connection.send(message).await?;

    let result = match server_connection.next().await {
        Some(Ok(Response::CreateUsers(result))) => result,
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    for (name, result) in result {
        match result {
            Ok(()) => println!("User '{}' created.", name),
            Err(err) => handle_create_user_error(err, &name),
        }
    }

    Ok(())
}

async fn drop_users(
    args: DeleteArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    let db_users = args.name.iter().map(trim_user_name_to_32_chars).collect();

    let message = Request::DropUsers(db_users);
    server_connection.send(message).await?;

    let result = match server_connection.next().await {
        Some(Ok(Response::DropUsers(result))) => result,
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    for (name, result) in result {
        match result {
            Ok(()) => println!("User '{}' deleted.", name),
            Err(err) => handle_drop_user_error(err, &name),
        }
    }

    Ok(())
}

async fn passwd_users(
    args: PasswdArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    let db_users = args.name.iter().map(trim_user_name_to_32_chars).collect();

    let message = Request::ListUsers(Some(db_users));
    server_connection.send(message).await?;

    let response = match server_connection.next().await {
        Some(Ok(Response::ListUsers(result))) => result,
        response => return erroneous_server_response(response),
    };

    let argv0 = std::env::args()
        .next()
        .unwrap_or("mysql-useradm".to_string());

    let users = response
        .into_iter()
        .filter_map(|(name, result)| match result {
            Ok(user) => Some(user),
            Err(err) => {
                handle_list_users_error(err, &name);
                None
            }
        })
        .collect::<Vec<_>>();

    for user in users {
        let password = read_password_from_stdin_with_double_check(&user.user)?;
        let message = Request::PasswdUser(user.user.to_owned(), password);
        server_connection.send(message).await?;
        match server_connection.next().await {
            Some(Ok(Response::PasswdUser(result))) => match result {
                Ok(()) => println!("Password updated for user '{}'.", &user.user),
                Err(_) => eprintln!(
                    "{}: Failed to update password for user '{}'.",
                    argv0, user.user,
                ),
            },
            response => return erroneous_server_response(response),
        }
    }

    server_connection.send(Request::Exit).await?;

    Ok(())
}

async fn show_users(
    args: ShowArgs,
    mut server_connection: ClientToServerMessageStream,
) -> anyhow::Result<()> {
    let db_users: Vec<_> = args.name.iter().map(trim_user_name_to_32_chars).collect();

    let message = if db_users.is_empty() {
        Request::ListUsers(None)
    } else {
        Request::ListUsers(Some(db_users))
    };
    server_connection.send(message).await?;

    let users: Vec<DatabaseUser> = match server_connection.next().await {
        Some(Ok(Response::ListAllUsers(result))) => match result {
            Ok(users) => users,
            Err(err) => {
                println!("Failed to list users: {:?}", err);
                return Ok(());
            }
        },
        Some(Ok(Response::ListUsers(result))) => result
            .into_iter()
            .filter_map(|(name, result)| match result {
                Ok(user) => Some(user),
                Err(err) => {
                    handle_list_users_error(err, &name);
                    None
                }
            })
            .collect(),
        response => return erroneous_server_response(response),
    };

    server_connection.send(Request::Exit).await?;

    for user in users {
        if user.has_password {
            println!("User '{}': password set.", user.user);
        } else {
            println!("User '{}': no password set.", user.user);
        }
    }

    Ok(())
}