gpt4 book ai didi

c++ - 在 C++ 中挂载 samba 共享

转载 作者:行者123 更新时间:2023-12-04 18:52:23 25 4
gpt4 key购买 nike

我正在开发一个必须在 Ubuntu 上挂载 samba 共享的项目。此项目将由非 root 用户使用。现在我正在使用一个名为 gvfs-mount 的应用程序。因为这不需要root密码来安装。
我的应用程序使用特定的命令行参数运行该可执行文件并且它可以工作,但错误检查很困难。我正在使用一个名为 pstreams 的库推出gvfs-mount并写入和读取它的标准输入/输出,但我可以预测应用程序何时将某些内容写入标准输出。这是一个问题,因为如果我想从 gvfs-mount的输出,但应用程序没有写任何东西,宿主应用程序将被阻塞,因为那将等待永远不会到来的东西。
我知道我可以使用 mount函数来自 sys/mount.h ,但这需要root权限。我的问题是:在 C++ 中是否有关于这个主题的 API、库或教程?
编辑:
正如电影人所说,我查看了 gvfs-mount 的源代码并转换为 C++。这是我非常基本的代码:

#include <gtkmm.h>

#include <stdexcept>
#include <iostream>

Glib::RefPtr<Gio::File> file;
Glib::RefPtr<Glib::MainLoop> main_loop;

void on_async_ready(Glib::RefPtr<Gio::AsyncResult>& result)
{
file->mount_enclosing_volume_finish(result);

main_loop->quit();
}

int main()
{
Gio::init();
Glib::init();

main_loop = Glib::MainLoop::create(false);

file = Gio::File::create_for_commandline_arg("smb://192.168.1.3/Memory\\ core");
Glib::RefPtr<Gio::MountOperation> mount_operation = Gio::MountOperation::create();
mount_operation->set_domain("domain");
mount_operation->set_username("user");
mount_operation->set_password("password");

try
{
file->mount_enclosing_volume(mount_operation, &on_async_ready);
}
catch(const Glib::Error& ex)
{
std::cerr << ex.what() << std::endl;
}

main_loop->run();

return 0;
}
问题是当我以普通用户身份运行此代码时,我得到以下输出:
(进程:5816):glibmm-CRITICAL **:
信号处理程序中未处理的异常(类型 Glib::Error):
域:g-io-error-quark
代码:0
什么:无法挂载 Windows 共享:不允许操作
当我以 sudo 运行时,我得到了这个:
(进程:5862):glibmm-CRITICAL **:
信号处理程序中未处理的异常(类型 Glib::Error):
域:g-io-error-quark
代码:15
什么:卷没有实现挂载
关于解决这个问题的任何建议?该代码应使用普通用户权限。
编辑2:
我更新了源代码,因为它是 uri 中的错误。我发现如果我将 gvfs-mount 作为 sudo 运行,我会收到与我的应用程序中相同的错误消息。所以我的想法是权限有问题。我的用户名属于 fuse 组,这很重要。
#include <gtkmm.h>

#include <iostream>

Glib::RefPtr<Gio::File> file;
Glib::RefPtr<Glib::MainLoop> main_loop;

void on_async_ready(Glib::RefPtr<Gio::AsyncResult>& result)
{
try
{
file->mount_enclosing_volume_finish(result);
}
catch(const Glib::Error& ex)
{
std::cerr << ex.what() << std::endl;
}

main_loop->quit();
}

int main()
{
Gio::init();
Glib::init();

main_loop = Glib::MainLoop::create(false);

file = Gio::File::create_for_commandline_arg("smb://192.168.1.3/Memory core");
Glib::RefPtr<Gio::MountOperation> mount_operation = Gio::MountOperation::create();
mount_operation->set_domain("domain");
mount_operation->set_username("user");
mount_operation->set_password("password");


file->mount_enclosing_volume(mount_operation, &on_async_ready);

main_loop->run();

return 0;
}

最佳答案

我能够在我的 Rust 应用程序中解决这个问题,它最初表现出与这个问题中报告的相同的行为。
解决方案是为 ask-password 注册回调。信号,使用此代码路径填写凭据,然后 - 最重要的是 - 调用 reply使用 Handled 进行挂载操作旗帜。
附加的 Rust 中的 PoC,也应该很容易转移到 C++:


use gio::prelude::*;
use glib::{self, clone};
use futures::prelude::*;
use gio::{AskPasswordFlags, MountMountFlags, MountOperation, MountOperationResult};

// read_file taken from https://github.com/gtk-rs/gtk-rs-core/blob/master/examples/gio_futures_await/main.rs#L29

async fn read_file(file: gio::File) -> Result<(), String> {
// Try to open the file.
let strm = file
.read_future(glib::PRIORITY_DEFAULT)
.map_err(|err| format!("Failed to open file: {}", err))
.await?;

// If opening the file succeeds, we asynchronously loop and
// read the file in up to 64 byte chunks and re-use the same
// vec for each read.
let mut buf = vec![0; 64];
let mut idx = 0;

loop {
let (b, len) = strm
.read_future(buf, glib::PRIORITY_DEFAULT)
.map_err(|(_buf, err)| format!("Failed to read from stream: {}", err))
.await?;

// Once 0 is returned, we know that we're done with reading, otherwise
// loop again and read another chunk.
if len == 0 {
break;
}

buf = b;

println!("line {}: {:?}", idx, std::str::from_utf8(&buf[0..len]).unwrap());

idx += 1;
}

// Asynchronously close the stream in the end.
let _ = strm
.close_future(glib::PRIORITY_DEFAULT)
.map_err(|err| format!("Failed to close stream: {}", err))
.await?;

Ok(())
}

// one could probably also use glib to drive the futures
// but this was more familiar to me

#[tokio::main]
async fn main() {
env_logger::init();

let c = glib::MainContext::default();

let file = gio::File::for_uri("smb://host/users/username/Desktop/test.txt");

// check whether the surrounding share is already mounted
let cancellable = gio::Cancellable::new();
if file.find_enclosing_mount(Some(&cancellable)).is_err() {
log::info!("Enclosing share not mounted, trying to mount it");

let mount_op = MountOperation::new();
mount_op.connect_ask_password(|op, msg, default_user, default_domain, flags| {
op.set_anonymous(false);
if flags.contains(AskPasswordFlags::NEED_USERNAME) {
op.set_username(Some("my-user"));
}
if flags.contains(AskPasswordFlags::NEED_PASSWORD) {
op.set_password(Some("my-password"));
}
if flags.contains(AskPasswordFlags::NEED_DOMAIN) {
op.set_domain(Some(default_domain)); // should not be required, let's see
}
// this is the important part!
op.reply(MountOperationResult::Handled);
});

let mount_result = file.mount_enclosing_volume_future(MountMountFlags::empty(), Some(&mount_op));
let mount_result = c.block_on(mount_result);
if let Err(err) = mount_result {
log::error!("Failed to mount: {}", err);
return
}
}

let future = async {
match read_file(file).await {
Ok(()) => (),
Err(err) => eprintln!("Got error: {}", err),
}
};

c.block_on(future);
}

关于c++ - 在 C++ 中挂载 samba 共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25739391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com