LINUX.ORG.RU

Сообщения neversleep

 

Смонтировать ntfs через fstab

Установил fedora 39 workstation на новый ноут, редактирую fstab чтобы автоматически монтировать ntfs раздел при загрузке:

UUID=01DA3A438D9F2D10 /media/data nfts3 umask=0 0 0

Вроде всё просто и точно такая же строка работает на другом ноуте, но после редактирования при перезагрузке выходит ошибка Cannot open access to console, the root account is locked, если нажать enter опять выходит то же самое сообщение и так по кругу.

Хотя если монтировать вручную sudo mount -t ntfs3 /dev/nvme0n1p1 /media/data -o umask=0 то всё работает.

 , ,

neversleep
()

Ошибка Certificiate invalid: certificate is not alive при попытке обновить Double Commander

При попытке обновить Double Commander на Fedora 38 (команда sudo dnf update -y --nogpgcheck) получаю ошибки:

Running transaction check
error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
  1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
      because: The primary key is not live
      because: Expired on 2023-03-22T20:10:23Z
  2. Key 61508B60C33A8925 invalid: key is not alive
      because: The primary key is not live
      because: Expired on 2023-03-22T20:10:23Z
error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
  1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
      because: The primary key is not live
      because: Expired on 2023-03-22T20:10:23Z
  2. Key 61508B60C33A8925 invalid: key is not alive
      because: The primary key is not live
      because: Expired on 2023-03-22T20:10:23Z
Transaction check succeeded.
Running transaction test
RPM: error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
RPM:   1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM:   2. Key 61508B60C33A8925 invalid: key is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM: error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
RPM:   1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM:   2. Key 61508B60C33A8925 invalid: key is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM: error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
RPM:   1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM:   2. Key 61508B60C33A8925 invalid: key is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM: error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
RPM:   1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM:   2. Key 61508B60C33A8925 invalid: key is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM: error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
RPM:   1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM:   2. Key 61508B60C33A8925 invalid: key is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM: error: Verifying a signature using certificate 41B5132F245C8E77743285ED61508B60C33A8925 (home:Alexx2000 OBS Project <home:Alexx2000@build.opensuse.org>):
RPM:   1. Certificiate 61508B60C33A8925 invalid: certificate is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
RPM:   2. Key 61508B60C33A8925 invalid: key is not alive
RPM:       because: The primary key is not live
RPM:       because: Expired on 2023-03-22T20:10:23Z
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'dnf clean packages'.
Error: Transaction test error:
  package doublecmd-gtk-1.2.0+svn11005+gitbb21348-937.1.x86_64 does not verify: Header V3 RSA/SHA256 Signature, key ID c33a8925: NOTTRUSTED
  package libunrar-6.2.12-2.1.x86_64 does not verify: Header V3 RSA/SHA256 Signature, key ID c33a8925: NOTTRUSTED

Сертификат импортировал sudo rpm --import "https://download.opensuse.org/repositories/home:/Alexx2000:/doublecmd-svn/Fedora_38/repodata/repomd.xml.key"

ЧЯДНТ?

 ,

neversleep
()

Как настроить SQUID и HTTPS?

На сервере стоит ubuntu 20.04, пытаюсь сделать себе прокси и чтобы https работал. Нашёл несколько статей, все они примерно одинакового содержания, как вот эта тема. В итоге у меня https через прокси не работает.

squid --version
Squid Cache: Version 4.13
Service Name: squid
Ubuntu linux

This binary uses OpenSSL 1.1.1f  31 Mar 2020. For legal restrictions on distribution see https://www.openssl.org/source/license.html

configure options:  '--build=x86_64-linux-gnu' '--prefix=/usr' '--includedir=${prefix}/include' '--mandir=${prefix}/share/man' '--infodir=${prefix}/share/info' '--sysconfdir=/etc' '--localstatedir=/var' '--disable-silent-rules' '--libdir=${prefix}/lib/x86_64-linux-gnu' '--runstatedir=/run' '--disable-maintainer-mode' '--disable-dependency-tracking' 'BUILDCXXFLAGS=-g -O2 -fdebug-prefix-map=/home/builder/ubuntu20/build/squid/squid-4.13=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now ' 'BUILDCXX=g++' '--with-build-environment=default' '--enable-build-info=Ubuntu linux' '--datadir=/usr/share/squid' '--sysconfdir=/etc/squid' '--libexecdir=/usr/lib/squid' '--mandir=/usr/share/man' '--enable-inline' '--disable-arch-native' '--enable-async-io=8' '--enable-storeio=ufs,aufs,diskd,rock' '--enable-removal-policies=lru,heap' '--enable-delay-pools' '--enable-cache-digests' '--enable-icap-client' '--enable-ssl' '--enable-follow-x-forwarded-for' '--enable-auth-basic=DB,fake,getpwnam,LDAP,NCSA,NIS,PAM,POP3,RADIUS,SASL,SMB' '--enable-auth-digest=file,LDAP' '--enable-auth-negotiate=kerberos,wrapper' '--enable-auth-ntlm=fake,SMB_LM' '--enable-external-acl-helpers=file_userip,kerberos_ldap_group,LDAP_group,session,SQL_session,time_quota,unix_group,wbinfo_group' '--enable-security-cert-validators=fake' '--enable-storeid-rewrite-helpers=file' '--enable-url-rewrite-helpers=fake' '--enable-eui' '--enable-esi' '--enable-icmp' '--enable-zph-qos' '--enable-ecap' '--disable-translation' '--with-swapdir=/var/spool/squid' '--with-logdir=/var/log/squid' '--with-pidfile=/run/squid.pid' '--with-filedescriptors=65536' '--with-large-files' '--with-default-user=proxy' '--enable-linux-netfilter' '--with-systemd' '--with-openssl' '--enable-ssl-crtd' 'build_alias=x86_64-linux-gnu' 'CFLAGS=-g -O2 -fdebug-prefix-map=/home/builder/ubuntu20/build/squid/squid-4.13=. -fstack-protector-strong -Wformat -Werror=format-security -Wall' 'LDFLAGS=-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now ' 'CPPFLAGS=-Wdate-time -D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -fdebug-prefix-map=/home/builder/ubuntu20/build/squid/squid-4.13=. -fstack-protector-strong -Wformat -Werror=format-security'

Конфиг:

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
acl all src all

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
#http_access allow localnet
http_access allow localhost

http_access allow authenticated
http_access allow all

# And finally deny all other access to this proxy
http_access deny all

http_port 3128 intercept ssl-bump generate-host-certificates=on dynamic_cert_mem_cache_size=4MB cert=/etc/squid/certs/squidca.pem

acl step1 at_step SslBump1
ssl_bump peek step1
ssl_bump bump all
sslproxy_cert_error allow all
sslproxy_flags DONT_VERIFY_PEER # Accept certificates that fail verification.

sslcrtd_program /usr/lib/squid/security_file_certgen -s /var/spool/squid/ssl_db/ -M 4MB

Сертификат сгенерировал так:

cd /etc/squid/certs/

sudo openssl req -new -newkey rsa:2048 -days 3650 -nodes -x509 -keyout squidca.pem -out squidca.pem

sudo openssl x509 -outform der -in squidca.pem -out squidca.crt

Затем скопировал его в /etc/pki/ca-trust/source/anchors/squidca.crt у себя локально и выполнил sudo update-ca-trust, так же пробовал импортировать непосредственно в браузер (в authorities). Firefox, например, говорит:

Secure Connection Failed

An error occurred during a connection to duckduckgo.com. PR_CONNECT_RESET_ERROR

    The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
    Please contact the website owners to inform them of this problem.

CURL вообще записает:

curl --proxy https://xxx.xxx.xxx.xxx:3128 -u 'user:password' https://google.com -vvv
*   Trying xxx.xxx.xxx.xxx:3128...
* Connected to xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx) port 3128 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/pki/tls/certs/ca-bundle.crt
*  CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):

Логи запуска:

-- The job identifier is 458725.
Mar 29 08:05:51 ubuntu-server squid[1508803]: 2022/03/29 08:05:51| WARNING: (B) '::/0' is a subnetwork of (A) '::/0'
Mar 29 08:05:51 ubuntu-server squid[1508803]: 2022/03/29 08:05:51| WARNING: because of this '::/0' is ignored to keep splay tree searching predictable
Mar 29 08:05:51 ubuntu-server squid[1508803]: 2022/03/29 08:05:51| WARNING: You should probably remove '::/0' from the ACL named 'all'
Mar 29 08:05:51 ubuntu-server squid[1508803]: 2022/03/29 08:05:51| ERROR: Directive 'sslproxy_flags' is obsolete.
Mar 29 08:05:51 ubuntu-server squid[1508803]: 2022/03/29 08:05:51| Created PID file (/run/squid.pid)
Mar 29 08:05:51 ubuntu-server squid[1508803]: Squid Parent: will start 1 kids
Mar 29 08:05:51 ubuntu-server squid[1508803]: Squid Parent: (squid-1) process 1508819 started
Mar 29 08:05:51 ubuntu-server squid[1508819]: 2022/03/29 08:05:51 kid1| WARNING: (B) '::/0' is a subnetwork of (A) '::/0'
Mar 29 08:05:51 ubuntu-server squid[1508819]: 2022/03/29 08:05:51 kid1| WARNING: because of this '::/0' is ignored to keep splay tree searching predictable
Mar 29 08:05:51 ubuntu-server squid[1508819]: 2022/03/29 08:05:51 kid1| WARNING: You should probably remove '::/0' from the ACL named 'all'
Mar 29 08:05:51 ubuntu-server squid[1508819]: 2022/03/29 08:05:51 kid1| ERROR: Directive 'sslproxy_flags' is obsolete.
Mar 29 08:05:51 ubuntu-server squid[1508819]: 2022/03/29 08:05:51 kid1| Set Current Directory to /var/spool/squid
Mar 29 08:05:51 ubuntu-server squid[1508819]: 2022/03/29 08:05:51 kid1| Creating missing swap directories
Mar 29 08:05:51 ubuntu-server squid[1508819]: 2022/03/29 08:05:51 kid1| No cache_dir stores are configured.
Mar 29 08:05:51 ubuntu-server squid[1508803]: Squid Parent: squid-1 process 1508819 exited with status 0
Mar 29 08:05:51 ubuntu-server squid[1508803]: 2022/03/29 08:05:51| Removing PID file (/run/squid.pid)
Mar 29 08:05:51 ubuntu-server squid[1508821]: 2022/03/29 08:05:51| WARNING: (B) '::/0' is a subnetwork of (A) '::/0'
Mar 29 08:05:51 ubuntu-server squid[1508821]: WARNING: (B) '::/0' is a subnetwork of (A) '::/0'
Mar 29 08:05:51 ubuntu-server squid[1508821]: 2022/03/29 08:05:51| WARNING: because of this '::/0' is ignored to keep splay tree searching predictable
Mar 29 08:05:51 ubuntu-server squid[1508821]: WARNING: because of this '::/0' is ignored to keep splay tree searching predictable
Mar 29 08:05:51 ubuntu-server squid[1508821]: 2022/03/29 08:05:51| WARNING: You should probably remove '::/0' from the ACL named 'all'
Mar 29 08:05:51 ubuntu-server squid[1508821]: WARNING: You should probably remove '::/0' from the ACL named 'all'
Mar 29 08:05:51 ubuntu-server squid[1508821]: 2022/03/29 08:05:51| ERROR: Directive 'sslproxy_flags' is obsolete.
Mar 29 08:05:51 ubuntu-server squid[1508821]: ERROR: Directive 'sslproxy_flags' is obsolete.
Mar 29 08:05:51 ubuntu-server squid[1508821]: Created PID file (/run/squid.pid)
Mar 29 08:05:51 ubuntu-server squid[1508821]: Squid Parent: will start 1 kids
Mar 29 08:05:51 ubuntu-server squid[1508821]: Squid Parent: (squid-1) process 1508823 started
Mar 29 08:05:51 ubuntu-server (squid-1)[1508823]: WARNING: (B) '::/0' is a subnetwork of (A) '::/0'
Mar 29 08:05:51 ubuntu-server (squid-1)[1508823]: WARNING: because of this '::/0' is ignored to keep splay tree searching predictable
Mar 29 08:05:51 ubuntu-server (squid-1)[1508823]: WARNING: You should probably remove '::/0' from the ACL named 'all'
Mar 29 08:05:51 ubuntu-server (squid-1)[1508823]: ERROR: Directive 'sslproxy_flags' is obsolete.
Mar 29 08:05:51 ubuntu-server squid[1508823]: Set Current Directory to /var/spool/squid
Mar 29 08:05:51 ubuntu-server squid[1508823]: Starting Squid Cache version 4.13 for x86_64-pc-linux-gnu...
Mar 29 08:05:51 ubuntu-server squid[1508823]: Service Name: squid
Mar 29 08:05:51 ubuntu-server squid[1508823]: Process ID 1508823
Mar 29 08:05:51 ubuntu-server squid[1508823]: Process Roles: worker
Mar 29 08:05:51 ubuntu-server squid[1508823]: With 1024 file descriptors available
Mar 29 08:05:51 ubuntu-server squid[1508823]: Initializing IP Cache...
Mar 29 08:05:51 ubuntu-server squid[1508823]: DNS Socket created at [::], FD 5
Mar 29 08:05:51 ubuntu-server squid[1508823]: DNS Socket created at 0.0.0.0, FD 10
Mar 29 08:05:51 ubuntu-server squid[1508823]: Adding nameserver 127.0.0.53 from /etc/resolv.conf
Mar 29 08:05:51 ubuntu-server squid[1508823]: helperOpenServers: Starting 5/32 'security_file_certgen' processes
Mar 29 08:05:51 ubuntu-server squid[1508823]: helperOpenServers: Starting 0/20 'basic_ncsa_auth' processes
Mar 29 08:05:51 ubuntu-server squid[1508823]: helperOpenServers: No 'basic_ncsa_auth' processes needed.
Mar 29 08:05:51 ubuntu-server squid[1508823]: Logfile: opening log daemon:/var/log/squid/access.log
Mar 29 08:05:51 ubuntu-server squid[1508823]: Logfile Daemon: opening log /var/log/squid/access.log
Mar 29 08:05:51 ubuntu-server squid[1508823]: Local cache digest enabled; rebuild/rewrite every 3600/3600 sec
Mar 29 08:05:51 ubuntu-server squid[1508823]: Store logging disabled
Mar 29 08:05:51 ubuntu-server squid[1508823]: Swap maxSize 0 + 262144 KB, estimated 20164 objects
Mar 29 08:05:51 ubuntu-server squid[1508823]: Target number of buckets: 1008
Mar 29 08:05:51 ubuntu-server squid[1508823]: Using 8192 Store buckets
Mar 29 08:05:51 ubuntu-server squid[1508823]: Max Mem  size: 262144 KB
Mar 29 08:05:51 ubuntu-server squid[1508823]: Max Swap size: 0 KB
Mar 29 08:05:51 ubuntu-server squid[1508823]: Using Least Load store dir selection
Mar 29 08:05:51 ubuntu-server squid[1508823]: Set Current Directory to /var/spool/squid
Mar 29 08:05:51 ubuntu-server squid[1508823]: Finished loading MIME types and icons.
Mar 29 08:05:51 ubuntu-server squid[1508823]: HTCP Disabled.
Mar 29 08:05:51 ubuntu-server squid[1508823]: Pinger socket opened on FD 26
Mar 29 08:05:51 ubuntu-server squid[1508823]: Squid plugin modules loaded: 0
Mar 29 08:05:51 ubuntu-server squid[1508823]: Adaptation support is off.
Mar 29 08:05:51 ubuntu-server squid[1508823]: Accepting NAT intercepted SSL bumped HTTP Socket connections at local=[::]:3128 remote=[::] FD 23 flags=41
Mar 29 08:05:51 ubuntu-server systemd[1]: Started Squid Web Proxy Server.
-- Subject: A start job for unit squid.service has finished successfully

Ещё иногда в логах появляется вот это:

ERROR: listen( FD 24, [::] [ job2], 256): (98) Address already in use

 ,

neversleep
()

Создать и вернуть структуру из функции

Не могу я понять эти ваши лайфтаймы. Есть, к примеру, вот такие структуры:

struct A {
    i: i64,
}

struct B<'a> {
    a: &'a A,
}

Я хочу сделать функцию, которая бы создавала и возвращала экземпляр B, но получаю ошибку use of undeclared lifetime name:

fn create_b(i: i64) -> B<'a> { // Ошибка в этой строке
    let a = A {
        i: i,
    };

    let b = B {
        a: &a,
    };

    return b;
}

А если указать результат функции как fn create_b(i: i64) -> B, то ошибка missing lifetime specifier. Я примерно понимаю, почему возникает ошикба, но как исправить не знаю.

Переписать этот код я не могу - в реале я использую библиотеку в которой примерно похожие стуктуры.

 ,

neversleep
()

Rubymine

Пощупал на днях демо версию, сам пользуюсь VSCode, так вот какие вопросы возникли:

  1. Моментально закрывает файлы, которые были были удалены с диска.
  2. Чтобы скопировать путь к файлу, нужно лезть аж ПКМ - Copy Path/Reference - выбрать нужное. В VSCode два пунтка в первом уровне ПКМ меню: Copy Path и Copy Relative Path.
  3. Не детектит ссылки в коде. В VSCode можно зажать Ctrl и кликнуть по ссылке, чтобы её открыть.
  4. С установленным плагином IdeaVim если назначить Ctrl+S на «Save All» не удаляет trailing whitespaces. Без плагина или через :w удаляет.
  5. Есть ли горячая клавиша, чтобы отформатировать код?
  6. Можно ли открыть два или более экземляра программы, т.е несколько разных проектов? Т.е если у тебя два проекта, бек и фронт, то нужно две разных IDE.
  7. Для поиска/замены в файлах открывается диалоговое окно, когда в VSCode это открывается справа, вместо дерева файлов (не прячет код).

Что действительно удобно, так это возможность Go to Definition в стороние гемы, которые используются в проекте.

Так вот мне интересно, за что тут платить $89.00 в год (индивидуальная лицензия)?

 ,

neversleep
()

inversifyjs

Сабж.

Насмотрелся я тут на проекты обложенные всякими декораторами @injectable, контейнерами, символами и интерфейсами (которые реализует один единственный класс) по самое не могу, аж в глазах рябит.

Кто-то это вообще использует? Чем оно лучше ванильного js/babel/ts?

@injectable()
export class My implements MyInterface {
    public constructor(
        @inject(Symbols.Logger) private readonly _log: Logger,
    ) {
    }
}

Что это такое? Почему нельзя сделать просто:

export class My implements MyInterface {
    private readonly log: Logger;

    public constructor()
    {
        this.log = new Logger();
    }
}

И не тащить за собой лишние пакеты?

 , ,

neversleep
()

Поделитесь годными темами для ФМ

Ищу годные темы для ФМ, в частности для Double Commander. Нашёл одну, но уж больно светлая. Супер популярную Solarized, я, конечно, видел, хочется чего-то другого.

 , ,

neversleep
()

Долго грузится Fedora

Уставновил Федору 31 на новое железо, во время загрузки она зависает примерно на минуту:

A start job is running for udev Wait for Complete Device Initialization

Я, конечно, понимаю, что это буквально означает, но мне не понятно, какое именно устройсто вызывает такие трудности при инициализации.

 ,

neversleep
()

После запуска Audacity пропал звук в наушниках

После запуска этого куска 💩 пропал звук в наушниках. Перепробовал всё, что знаю: alsamixer, pavucontrol, гномовские настройки звука и даже перезагрузку сделал. В pavucontrol показывает, что звук идёт, но при этом его совсем не слышно, если выдернуть наушники, то через динамики звук идёт. Как вернуть обратно?

 , ,

neversleep
()

Тихий звук airpods в Fedora

Подключил airpods 2, звук идёт но довольно тихо, ощущение, что в районе 30-40% от максимальной громкости. Нашёл вот эту страницу, но проблему это не решило (и на этом мои полномочия всё), что ещё здесь можно сделать чтобы увеличить громкость?

Fedora 31, gnome 3.34.2.

 ,

neversleep
()

Evince не ищет кириллицу

С тех пор как установил fedora 30 при попытке найти текст на кириллице в evince он ничего не находит. Как это лечится? Пользуюсь пока альтернативным софтом.

Язык системы английский.

 ,

neversleep
()

Советы по проектированию мессенджера

Делаю простой мессенджер на сокетах, TCP/IP. Есть клиент и сервер, дошёл до этапа обработки запросов и задумался над тем, каким образом наиболее труЪшным ооп путём организовать приём и обработку пакетов. Пакеты могут быть разные, черновой вариант такой:

enum RequestType {
    Register,
    Authenticate,
    Message, // текстовое сообщение
    Attachment, // файл
};

Пока идея такая:

  • Все пакеты первым полем должны содержать int type
  • Все пакеты кроме Attachment вторым полем будут иметь поле unsigned size, а далее JSON рамером в size с необходимыми полями
  • Attachment, в отличие от остальных, не JSON, у него три поля: кому recipient, имя файла char name[32] и его размер unsigned size, далее идут данные

Приём пакетов делаю так:

void Client::start()
{
    char *buffer;
    unsigned long bytes;

    m_socket->setBlocking(false); // неблокирующий режим

    while (true) {
        bytes = m_socket->waitForRead();

        if (bytes == 0) {
            // Disconnected
            delete m_socket;
            return;
        }

        // Вот здесь нужно организовать приём и формирование пакетов

        buffer = new char[bytes];

        m_socket->recv(&buffer[0], bytes);

        delete []buffer;
    }
}

Конечно можно решить задачу «в лоб», но мне интересно:

  • Как наиболее правильно с точки зрения ооп сделать задуманное? Что-то мне подсказывает для каждого пакета создать класс, которому передавать buffer и bytes, который будет формировать пакет?
  • Какие наиболее подходящие паттерны для подобных задач?
  • Где и как лучше всего осуществлять проверку аутентифицирован ли пользователь, или нет?

Может у кого есть хорошие примеры. Thanks in advance, так сказатб.

 ,

neversleep
()

double free or corruption (out)

Есть класс Matrix, в конструкторе память динамически резервируется, в деструкторе - освобождается, но при попытке освободить память деструктор терпит фиаско с сообщением double free or corruption (out). Это происходит если cols>rows, т.е при Matrix(3, 3) исключения нет, а вот при Matrix(3, 4) есть.

struct Matrix
{
    double **a;
    unsigned rows, cols;

    Matrix(const unsigned rows, const unsigned cols):
        rows(rows),
        cols(cols)
    {
        a = new double*[rows];

        for (unsigned i = 0; i < cols; ++i) {
            a[i] = new double[cols];
        }
    }

    ~Matrix()
    {
        for (unsigned i = 0; i < rows; ++i) {
            delete []a[i]; // double free or corruption (out)
        }

        delete []a;
    }
};

int main()
{
    Matrix m(3, 4);
    return 0;
}
Пробовал использовать malloc/calloc/free - та же ошибка.

 

neversleep
()

deadbeef, пропал звук

Fedora. В системе есть звук, а в deadbeef нет, в mpv, к примеру, тоже есть звук. Последние действия - игрался с teamviewer и syngery(уже удалён). С дефолтным конфигом запускал, ноут включал/выключал - не помогло. Куда копать?

Настройки звука: https://imgur.com/a/Vuyzl , громкость на максимум.

 ,

neversleep
()

Автомонтирование, рвать его мать

Хочу настроить автомонтирование usb накопителей(флешек). Погуглил немного, и создал такое правило для eudev:

/etc/udev/rules.d/automount.rules

KERNEL!="sd[c-z]*", GOTO="automount_end"

ACTION=="add", ENV{DEVTYPE}=="partition", RUN+="/usr/bin/udisksctl mount -b %N"
ACTION=="remove", ENV{DEVTYPE}=="partition", RUN+="/usr/bin/udisksctl unmount -b %N"

LABEL="automount_end"

Оно срабатывает только один раз - после перезапуска eudev /etc/init.d/udev restart. Дальше автомонтирование перестаёт работать, udisksctl выдаёт такую ошибку:

Error looking up object for device /dev/sde1

 , ,

neversleep
()

Не собирается deadbeef, а static версия не запускается

Лог сборки: http://pastebin.com/jNr0C1vq

Ну ок, скачал static версию, закинул в /opt/deadbeef, ln -sf /opt/deadbeef/deadbeef /opt/bin, запускаю:

nick@gentoo ~> deadbeef
starting deadbeef 0.6.2 [static]
server_start
searching for GUI plugins in /home/nick/.local/lib64/deadbeef
searching for GUI plugins in /home/nick/.local/lib/deadbeef
searching for GUI plugins in /opt/deadbeef/lib/deadbeef
load gui plugin
selected GUI plugin not found or failed to load, trying to find another GUI plugin
loading plugins from /home/nick/.local/lib64/deadbeef
loading plugins from /home/nick/.local/lib/deadbeef
loading plugins from /opt/deadbeef/lib/deadbeef
failed to find output plugin!

А если выполнить /opt/bin/deadbeef или /opt/deadbeef/deadbeef, то запускается нормально.

nick@gentoo ~> which deadbeef
/opt/bin/deadbeef

В качестве временного решения наваял такой скрипт:

#!/bin/bash

/opt/deadbeef/deadbeef "$@"

Но, пардон, какого чёрта? Почему не запускается через ссылку(без указания полного пути)?

 ,

neversleep
()

Нет звука в gentoo

Всем привет.

Установил gentoo(первый раз, да), и вот уже джва дня как я сижу без звука, джва долгих дня... и в этом вся проблема - звука нет, совсем... его просто нет.

Конфиг ядра
lspci -knn

dmesg | grep -i sound

[    0.298511] Advanced Linux Sound Architecture Driver Initialized.
[    1.876688]   No soundcards found.
[    1.879105] sound hdaudioC0D2: No codec parser is available
[    1.962511] sound hdaudioC1D0: No codec parser is available

aplay -l

**** List of PLAYBACK Hardware Devices ****
card 2: pcsp [pcsp], device 0: pcspeaker [pcsp]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

alsamixer вместо эквалайзеров пишет «This sound device does not have any controls»(но по F6(Select sound card) выводит список звуковых карт).

lsmod | grep snd

snd_pcsp                7790  0

cat /proc/asound/cards

 0 [SB             ]: HDA-Intel - HDA ATI SB
                      HDA ATI SB at 0xfcff4000 irq 16
 1 [NVidia         ]: HDA-Intel - HDA NVidia
                      HDA NVidia at 0xfeb7c000 irq 19
 2 [pcsp           ]: PC-Speaker - pcsp
                      Internal PC-Speaker at port 0x61

rmmod hda_snd_intel

rmmod: ERROR: Module snd_hda_intel is builtin.
// Почему «builtin»? Ведь при конфигурировании звука, я практически везде поставил «M».

 , , ,

neversleep
()

Получить элементы массива не существующие в таблице

1) Есть таблица пользователей, в которой, к примеру, только 1 поле «username».
2) Имеется массив с именами пользователей ['user1', 'user2', 'user3', ...].

Нужно с помощью sql запроса получить список имен пользователей из массива, которых нет в таблице, причём, имена должны быть не чувствительны к регистру. Я кое-что наговнокодил, интересует, может есть иной способ сделать это, как-нибудь, по-красивей?

 

neversleep
()

VirtualBox, modprobe: ERROR: could not insert 'vboxdrv': Invalid argument

Установил linux-lts, после чего при попытке запустить какую-нибудь витр. машину появляется сообщение об ошибке:

The VirtualBox Linux kernel driver (vboxdrv) is either not loaded or there is a permission problem with /dev/vboxdrv. Please reinstall the kernel module by executing

'pacman -S virtualbox-host-modules'

as root. If you don't use our stock kernel, install virtualbox-host-dkms and execute dkms autoinstall .

Установил virtualbox-host-modules-lts, выполнил dkms autoinstall, но ошибка не ушла, а при попытке выполнить modprobe vboxdrv получаю:

modprobe: ERROR: could not insert 'vboxdrv': Invalid argument

Ещё я наустанавливал всяких-разных virtualbox-* пакетов, но добился только того, что моё душевное равновесие было окончательно нарушено... и вот я здесь... пожалуйста, люди, помогите мне решить эту проблему.

 , ,

neversleep
()

zsh, debian и символ «^»?

Я чето не понял, пишу apt-cache search ^alsa- - получаю пустой выхлоп, пишу тоже самое в bash - все нормально(получаю результат поиска), но если заэкранировать ^ в z shell apt-cache search \^alsa-, то все тоже становиться нормально - почему?

PS
echo ^ в zsh выводит тоже самое что и ls Почему?(2), Алиас?
PPS
Debian - гостевая ОС, VirtualBox 4.3.16-1, хост ОС - Linux 3.16.2-1-ARCH #1 SMP PREEMPT Sat Sep 6 13:12:51 CEST 2014 x86_64 GNU/Linux

 , , ,

neversleep
()

RSS подписка на новые темы