File indexing completed on 2024-04-21 15:07:58

0001 // Copyright (c) 2015 Pino Toscano <pino@kde.org>
0002 //
0003 // This program is free software; you can redistribute it and/or
0004 // modify it under the terms of the GNU General Public License
0005 // version 2 as published by the Free Software Foundation.
0006 //
0007 // This program is distributed in the hope that it will be useful,
0008 // but WITHOUT ANY WARRANTY; without even the implied warranty of
0009 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0010 // General Public License for more details.
0011 //
0012 // You should have received a copy of the GNU General Public License
0013 // along with this program; see the file COPYING.  If not, write to
0014 // the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
0015 // Boston, MA 02110-1301, USA.
0016 
0017 #include "connectioncookie.h"
0018 
0019 #include <QDataStream>
0020 #include <QDir>
0021 #include <QFile>
0022 #include <QFileInfo>
0023 #include <QStandardPaths>
0024 
0025 static const int ConnectionCookieVersion = 1;
0026 
0027 static QString filePath()
0028 {
0029     return QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/atlantik.cookie");
0030 }
0031 
0032 ConnectionCookie::ConnectionCookie(const QString &host, int port, const QString &cookie)
0033     : m_host(host)
0034     , m_port(port)
0035     , m_cookie(cookie)
0036 {
0037     QFile f(filePath());
0038     QDir().mkpath(QFileInfo(f).absolutePath());
0039     if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate))
0040         return;
0041 
0042     QDataStream out(&f);
0043     out.setVersion(QDataStream::Qt_4_6);
0044     out << ConnectionCookieVersion;
0045     out << m_host;
0046     out << m_port;
0047     out << m_cookie;
0048 }
0049 
0050 ConnectionCookie::ConnectionCookie() : m_port(-1)
0051 {
0052 }
0053 
0054 ConnectionCookie::~ConnectionCookie()
0055 {
0056     QFile::remove(filePath());
0057 }
0058 
0059 ConnectionCookie *ConnectionCookie::read()
0060 {
0061     QFile f(filePath());
0062     if (!f.exists())
0063         return nullptr;
0064     if (!f.open(QIODevice::ReadOnly))
0065         return nullptr;
0066 
0067     QDataStream in(&f);
0068     in.setVersion(QDataStream::Qt_4_6);
0069     int version;
0070     in >> version;
0071     if (version != ConnectionCookieVersion)
0072         return nullptr;
0073 
0074     ConnectionCookie *cookie = new ConnectionCookie();
0075     in >> cookie->m_host;
0076     in >> cookie->m_port;
0077     in >> cookie->m_cookie;
0078     return cookie;
0079 }