Russian Qt Forum
Сентябрь 27, 2024, 07:16 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1] 2 3   Вниз
  Печать  
Автор Тема: Генерация .torrent файла  (Прочитано 26743 раз)
XpycT
Гость
« : Август 04, 2009, 18:44 »

Доброго времени суток.
Прошу вашей помощи в доделке генерации .torrent файла (не каталога). Дело в том, что остался только хеш pieces, но никак не получается его сделать..точнее не пойму что именно для него надо. Вот что у меня имеется
testapp.h
Код
C++ (Qt)
#ifndef TESTAPP_H
#define TESTAPP_H
 
#include <QDialog>
 
class testApp : public QDialog
{
   Q_OBJECT
public:
   testApp(QWidget *parent=0);
private slots:
   void generate();
};
 
#endif // TESTAPP_H
 
testapp.cpp
Код
C++ (Qt)
#include <QtGui>
#include "testapp.h"
 
testApp::testApp(QWidget *parent):QDialog(parent)
{
   QPushButton *openbtn=new QPushButton("OpenFile");
   QPushButton *genbtn=new QPushButton("Generate");
 
   QVBoxLayout *layout=new QVBoxLayout;
   layout->addWidget(openbtn);
   layout->addWidget(genbtn);
 
   setLayout(layout);
   connect(openbtn,SIGNAL(clicked()),this,SLOT(generate()));
}
void testApp::generate()
{
   QString announce="http://donald.org.ua/tracker/announce.php";
   QString createdby="BitTorrent/6120";
   int pieceslength= 256*1024;
   QString torrentcontent;
 
   QString fileName = QFileDialog::getOpenFileName(this,tr("Select Image"),
                                      QApplication::applicationDirPath(),
                                      tr("All Files (*.*)"));
   if(fileName.isEmpty())
           return;
 
   QFile file(fileName);
   QFileInfo fi(file);    
   if (!file.open(QIODevice::ReadOnly))
           return;
 
   QByteArray pieces = file.readAll();
   QByteArray tmp;
   QCryptographicHash *hash=new QCryptographicHash(QCryptographicHash::Sha1);
   for (int i = 0; i < pieces.size(); i += 20){
               hash->reset();
               hash->addData(pieces.mid(i, 20));
               tmp.append(hash->result());
           }
 
 
   //hash->addData(pieces);
 
   torrentcontent = QString("d8:announce%1:%2")
                    .arg(announce.length()).arg(announce);
   torrentcontent.append(QString("10:created by%1:%2")
                         .arg(createdby.length()).arg(createdby));
   torrentcontent.append(QString("13:creation datei%1")
                         .arg(QDateTime::currentDateTime().currentDateTime().toTime_t()));
   torrentcontent.append(QString("e8:encoding5:UTF-84:infod6:lengthi%1e4:name%2:%3")
                         .arg(file.size()).arg(fi.fileName().length()).arg(fi.fileName()));
   torrentcontent.append(QString("12:piece lengthi%1e6:pieces%2:")
                         .arg(pieceslength).arg(hash->result().length()));
 
    QFile data("output.torrent");
    if (data.open(QFile::WriteOnly)) {
        QTextStream out(&data);
        out << torrentcontent << tmp;
 
    }
    data.close();
}
 
Ссылки на спецификацию формата:
http://blog.bitcomet.com/bitcomet/post_413/
http://bittorrent.org/beps/bep_0003.html
http://wiki.theory.org/BitTorrentSpecification

Как я понял, надо прочитать весь файл, разбить его по 20 байт, и эти байты закриптовать в Sha1. Но как не пытаюсь сделать - созданный файл отличается от созданного в клиенте, и при его открытии выпадает сообщение о не битом формате Грустный
Записан
Rcus
Гость
« Ответ #1 : Август 04, 2009, 19:25 »

Нет, 20 байт это длина SHA1 хеша. До хешей есть поле длины куска... /* оставлю свои идеи по поводу еще одного торрент клиента при себе */
Записан
XpycT
Гость
« Ответ #2 : Август 04, 2009, 20:06 »

До хешей есть поле длины куска...
Если оно и есть, то уже в самом хеше, ибо все , кроме последнего хеша генерируется правильно (пробовал заменить оригинальный текст сгенерированным. Все прекрасно качалось).
Вопрос остается открыт Улыбающийся
Записан
SimpleSunny
Гость
« Ответ #3 : Август 04, 2009, 20:38 »

Цитировать
Если оно и есть, то уже в самом хеше, ибо все , кроме последнего хеша генерируется правильно (пробовал заменить оригинальный текст сгенерированным. Все прекрасно качалось).
Вопрос остается открыт Улыбающийся
Немного оошибаешся. Вот выдержка из http://wiki.theory.org/BitTorrentSpecification
Цитировать
This section contains the field which are common to both mode, "single file" and "multiple file".

    * piece length: number of bytes in each piece (integer)
    * pieces: string consisting of the concatenation of all 20-byte SHA1 hash values, one per piece (byte string, i.e. not urlencoded)
т. е. разбиваем файл на куски размером piece length и применяем к ним функцию SHA1.
Записан
XpycT
Гость
« Ответ #4 : Август 04, 2009, 22:33 »

т. е. разбиваем файл на куски размером piece length и применяем к ним функцию SHA1.
Я то понял, и бью по pieces length
Код
C++ (Qt)
   int pieceslength= 64*1024;
   QByteArray pieces = QString(file.readAll()).toAscii();
   QByteArray tmp;
   QCryptographicHash *hash=new QCryptographicHash(QCryptographicHash::Sha1);
   for (int i = 0; i < pieces.size(); i += pieceslength){
               hash->reset();
               hash->addData(pieces.mid(i, pieceslength));
               tmp.append(hash->result());
           }
   qDebug()  << tmp;
Но как на зло - результат не совпадает с тем, который должен получиться Грустный
« Последнее редактирование: Август 04, 2009, 22:40 от XpycT » Записан
niXman
Гость
« Ответ #5 : Август 04, 2009, 22:45 »

А откуда ты знаешь какой должен получиться?

Читать весь файл в память - плохая идея.

Зачем создавать велосипед? Возьми код любого торрент клиента, выдери оттуда что нужно, и все.
Записан
XpycT
Гость
« Ответ #6 : Август 04, 2009, 22:57 »

А откуда ты знаешь какой должен получиться?
Cравнение по содержимому моего и "правельного" торрента, созданого с одного файла.
Читать весь файл в память - плохая идея.
Я понимаю, но на время разработки пойдет т.к. тестирую на файлике в 516кб
Зачем создавать велосипед? Возьми код любого торрент клиента, выдери оттуда что нужно, и все.
Все что я смотрел, используют libtorrent, которая еще и boost за собою тянет, да и к тому же как не крутил, под MinGW+Windows крикрутить ее к проекту не вышло Улыбающийся
Записан
niXman
Гость
« Ответ #7 : Август 04, 2009, 23:05 »

Цитировать
Все что я смотрел, используют libtorrent, которая еще и boost за собою тянет
В libtorrent эта часть легко модифицируется чтоб работать без boost. Не хочешь выдерать, посмотри как это там реализовано.

Цитировать
да и к тому же как не крутил, под MinGW+Windows крикрутить ее к проекту не вышло
У меня на оборот. Мингв-ом собирается, а вот студию заставить не получается.
Записан
XpycT
Гость
« Ответ #8 : Август 05, 2009, 13:57 »

У меня на оборот. Мингв-ом собирается
Не мог бы ты подсказать как правильно собрать его под виндой. Я скачал boostи libtorrent-rasterbar-0.14.4, прописал в системные переменные BOOST_BUILD_PATH и BOOST_ROOT и в бусте в user-config.jam поставил using gcc ;, но когда собираю libtorrent
Код:
bjam gcc link=static boost=source
с boost_1_34_0 получаю ошибку
Код:
BOOST_ROOT = d:\Qt4_tutorial\addin\boost_1_34_0
OS = NT
Building Boost.Regex with the optional Unicode/ICU support disabled.
Please refer to the Boost.Regex documentation for more information
(don't panic: this is a strictly optional feature).
error: Unable to find file or target named
error:     '/boost/system//boost_system'
error: referred from project at
error:     '.'
а в  boost_1_39_0
Код:
D:\Qt4_tutorial\addin\libtorrent-rasterbar-0.14.4>bjam gcc link=static boost=sou
rce
BOOST_ROOT = d:\Qt4_tutorial\addin\boost_1_39_0
OS = NT
WARNING: No python installation configured and autoconfiguration
         failed.  See http://www.boost.org/libs/python/doc/building.html
         for configuration instructions or pass --without-python to
         suppress this message and silently skip all Boost.Python targets
...patience...
...patience...
...found 2161 targets...
...updating 75 targets...
gcc.compile.c++ bin\gcc-mingw-3.4.5\debug\boost-source\link-static\threading-mul
ti\src\kademlia\dht_tracker.o
In file included from d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/microse
c_time_clock.hpp:23,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/posix_t
ime/posix_time_types.hpp:11,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/detail/selec
t_reactor.hpp:25,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/impl/io_serv
ice.ipp:27,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/io_service.h
pp:550,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/basic_io_obj
ect.hpp:20,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/basic_socket
_acceptor.hpp:20,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/ip/tcp.hpp:2
0,
                 from include/libtorrent/socket.hpp:60,
                 from include/libtorrent/kademlia/node_entry.hpp:37,
                 from include/libtorrent/kademlia/routing_table.hpp:50,
                 from include/libtorrent/kademlia/node.hpp:40,
                 from src\kademlia\dht_tracker.cpp:45:
d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/filetime_functions.hpp: In fu
nction `uint64_t boost::date_time::winapi::file_time_to_microseconds(const FileT
imeT&)':
d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/filetime_functions.hpp:101: w
arning: left shift count >= width of type
include/libtorrent/bencode.hpp: In function `void libtorrent::detail::bdecode_re
cursive(InIt&, InIt, libtorrent::entry&, bool&, int) [with InIt = const char*]':

include/libtorrent/bencode.hpp:392:   instantiated from `libtorrent::entry libto
rrent::bdecode(InIt, InIt) [with InIt = const char*]'
src\kademlia\dht_tracker.cpp:447:   instantiated from here
include/libtorrent/bencode.hpp:250: error: `_strtoi64' was not declared in this
scope
include/libtorrent/bencode.hpp:250: warning: unused variable '_strtoi64'

    "g++"  -ftemplate-depth-128 -O0 -fno-inline -Wall -g -mthreads -Wno-missing-
braces -fno-strict-aliasing -DBOOST_ALL_NO_LIB -DBOOST_FILESYSTEM_STATIC_LINK=1
-DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DBOOST_SYSTEM_STATIC_LINK=1 -DBOOST_T
HREAD_USE_LIB -DBOOST_THREAD_USE_LIB=1 -DTORRENT_DEBUG -DTORRENT_DISABLE_GEO_IP
-DTORRENT_USE_OPENSSL -DUNICODE -DWIN32 -DWIN32_LEAN_AND_MEAN -D_FILE_OFFSET_BIT
S=64 -D_UNICODE -D_WIN32 -D_WIN32_WINNT=0x0500 -D__USE_W32_SOCKETS  -I"d:\Qt4_tu
torial\addin\boost_1_39_0" -I"\usr\sfw\include" -I"d:\Qt4_tutorial\addin\boost_1
_39_0" -I"include" -I"include\libtorrent" -I"zlib" -c -o "bin\gcc-mingw-3.4.5\de
bug\boost-source\link-static\threading-multi\src\kademlia\dht_tracker.o" "src\ka
demlia\dht_tracker.cpp"

...failed gcc.compile.c++ bin\gcc-mingw-3.4.5\debug\boost-source\link-static\thr
eading-multi\src\kademlia\dht_tracker.o...
gcc.compile.c++ bin\gcc-mingw-3.4.5\debug\boost-source\link-static\threading-mul
ti\src\kademlia\find_data.o
In file included from d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/microse
c_time_clock.hpp:23,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/posix_t
ime/posix_time_types.hpp:11,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/detail/selec
t_reactor.hpp:25,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/impl/io_serv
ice.ipp:27,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/io_service.h
pp:550,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/basic_io_obj
ect.hpp:20,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/basic_socket
_acceptor.hpp:20,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/ip/tcp.hpp:2
0,
                 from include/libtorrent/socket.hpp:60,
                 from include/libtorrent/kademlia/node_entry.hpp:37,
                 from include/libtorrent/kademlia/routing_table.hpp:50,
                 from include/libtorrent/kademlia/traversal_algorithm.hpp:40,
                 from include/libtorrent/kademlia/find_data.hpp:38,
                 from src\kademlia\find_data.cpp:35:
d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/filetime_functions.hpp: In fu
nction `uint64_t boost::date_time::winapi::file_time_to_microseconds(const FileT
imeT&)':
d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/filetime_functions.hpp:101: w
arning: left shift count >= width of type
...interrupted
gcc.compile.c++ bin\gcc-mingw-3.4.5\debug\boost-source\link-static\threading-mul
ti\src\kademlia\node.o
In file included from src\kademlia\node.cpp:42:
include/libtorrent/hasher.hpp:46:25: openssl/sha.h: No such file or directory
In file included from src\kademlia\node.cpp:42:
include/libtorrent/hasher.hpp:116: error: `SHA_CTX' does not name a type
include/libtorrent/hasher.hpp: In constructor `libtorrent::hasher::hasher()':
include/libtorrent/hasher.hpp:90: error: `m_context' was not declared in this sc
ope
include/libtorrent/hasher.hpp:90: error: `SHA1_Init' was not declared in this sc
ope
include/libtorrent/hasher.hpp:90: warning: unused variable 'm_context'
include/libtorrent/hasher.hpp:90: warning: unused variable 'SHA1_Init'
include/libtorrent/hasher.hpp: In constructor `libtorrent::hasher::hasher(const
char*, int)':
include/libtorrent/hasher.hpp:93: error: `m_context' was not declared in this sc
ope
include/libtorrent/hasher.hpp:93: error: `SHA1_Init' was not declared in this sc
ope
include/libtorrent/hasher.hpp:96: error: `SHA1_Update' was not declared in this
scope
include/libtorrent/hasher.hpp:93: warning: unused variable 'SHA1_Init'
include/libtorrent/hasher.hpp:96: warning: unused variable 'SHA1_Update'
include/libtorrent/hasher.hpp: In member function `void libtorrent::hasher::upda
te(const char*, int)':
include/libtorrent/hasher.hpp:102: error: `m_context' was not declared in this s
cope
include/libtorrent/hasher.hpp:102: error: `SHA1_Update' was not declared in this
 scope
include/libtorrent/hasher.hpp:102: warning: unused variable 'm_context'
include/libtorrent/hasher.hpp:102: warning: unused variable 'SHA1_Update'
include/libtorrent/hasher.hpp: In member function `libtorrent::sha1_hash libtorr
ent::hasher::final()':
include/libtorrent/hasher.hpp:108: error: `m_context' was not declared in this s
cope
include/libtorrent/hasher.hpp:108: error: `SHA1_Final' was not declared in this
scope
include/libtorrent/hasher.hpp:108: warning: unused variable 'm_context'
include/libtorrent/hasher.hpp:108: warning: unused variable 'SHA1_Final'
include/libtorrent/hasher.hpp: In member function `void libtorrent::hasher::rese
t()':
include/libtorrent/hasher.hpp:112: error: `m_context' was not declared in this s
cope
include/libtorrent/hasher.hpp:112: error: `SHA1_Init' was not declared in this s
cope
include/libtorrent/hasher.hpp:112: warning: unused variable 'm_context'
include/libtorrent/hasher.hpp:112: warning: unused variable 'SHA1_Init'
In file included from d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/microse
c_time_clock.hpp:23,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/posix_t
ime/posix_time_types.hpp:11,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/detail/selec
t_reactor.hpp:25,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/impl/io_serv
ice.ipp:27,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/io_service.h
pp:550,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/basic_io_obj
ect.hpp:20,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/basic_socket
_acceptor.hpp:20,
                 from d:/Qt4_tutorial/addin/boost_1_39_0/boost/asio/ip/tcp.hpp:2
0,
                 from include/libtorrent/socket.hpp:60,
                 from include/libtorrent/kademlia/rpc_manager.hpp:45,
                 from src\kademlia\node.cpp:45:
d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/filetime_functions.hpp: In fu
nction `uint64_t boost::date_time::winapi::file_time_to_microseconds(const FileT
imeT&)':
d:/Qt4_tutorial/addin/boost_1_39_0/boost/date_time/filetime_functions.hpp:101: w
arning: left shift count >= width of type
и далее аналогичные ошибки.

Ну или на крайний случай можешь выложить откомпиленную либу Грустный

Записан
spirit
Гость
« Ответ #9 : Август 05, 2009, 14:22 »

с кьюти идет экзампл торрента QTDIR\examples\network\torrent\ или так не то что нужно?
Записан
XpycT
Гость
« Ответ #10 : Август 05, 2009, 14:42 »

с кьюти идет экзампл торрента QTDIR\examples\network\torrent\ или так не то что нужно?

Да идет, и сделали там можно сказать все, кроме создание самого торрента, я там смотрел как они считывают хеш файлов, и по аналогу пробовал его записать..но не совпадает , пишет .torrent file is broken"Улыбающийся
Записан
spirit
Гость
« Ответ #11 : Август 05, 2009, 14:53 »

ясно. с тонкостями не разбирался просто.  Улыбающийся
Записан
XpycT
Гость
« Ответ #12 : Август 06, 2009, 08:29 »

Полтора дня с бубном вокруг библиотеки дали свое - смог нормально собрать проект windows+mingw+Qt.

Смешно лишь то - что под msvc собирается сразу и без внесения изменений в либу..а вот с mingw конечно обидно Грустный.

Небольшой солюшен, может кому пригодится.
  • Качаем и собираем и статически собираем boost_1_39_0
  • Качаем Curl (в нем сразу есть и OpenSSL)
  • Качаем libtorrent-rasterbar-0.14.4 и вносим небольшие изменения:
1) Если компилятор выдает ошибки на _strtoi64, то в \libtorrent-rasterbar-0.14.4\include\libtorrent\bencode.hpp добавляем
   
Код
C++ (Qt)
#define _strtoi64(a,b,c) strtoll(a,b,c)
2) Если компилятор ругается на PROTECTION_LEVEL_UNRESTRICTED(для IPv6), то в \libtorrent-rasterbar-0.14.4\src\session_impl.cpp в начало добавляем
   
Код
C++ (Qt)
#define PROTECTION_LEVEL_UNRESTRICTED 10

3) Если ошибка libtorrent.a(file.o):file.cpp:(.text+0x717): undefined reference to `libtorrent::safe_convert(std::string const&)', то тут нашел такое решение.
В файле \libtorrent-rasterbar-0.14.4\include\libtorrent\storage.hpp и \libtorrent-rasterbar-0.14.4\src\file.cpp удаляем директиву TORRENT_USE_WPATH, но не ее содержимое(строку оставляем).
Если начнет материться на wpath, тогда надо будет еще в \libtorrent-rasterbar-0.14.4\src\storage.cpp в самом начале удалить директиву TORRENT_USE_WPATH(где функция safe_convert) но содержимое оставить, а вот дальше удялять все что в #if TORRENT_USE_WPATH ...#elseif, а то что в #elseif...#endif оставлять.

В результате библиотека должна нормально собраться под MinGW. Ну а в проект слинковать по аналогу с джамовского файла, тоесть

Код:
TEMPLATE = app
TARGET = console
DEPENDPATH += .
INCLUDEPATH += . \
    ../../addin/libtorrent-rasterbar-0.14.4/include \ # путь к инклудам libtorrent
    ../../addin/boost_1_39_0 # наш буст
CONFIG += staticlib \
    static \
    console

SOURCES += main.cpp
# ну и либы от буста filesystem, thread, system, сам libtorrent, и если испольовали SSH то линкуем и виндосовские библиотеки.
win32:LIBS += -llibboost_system-mgw34-mt-1_39 -llibtorrent -llibboost_filesystem-mgw34 -llibboost_thread-mgw34-mt-1_39 -lws2_32 -lwsock32 -ladvapi32 -lwinmm -lssl32 -leay32 -lssleay32 -luser32 -lshell32 -lgdi32 -lcrypto -lssl

Может можно и проще исправить ошибки...допустим в config.hpp есть #define TORRENT_USE_WPATH 1, из-за которого весь геморрой, но когда я пытался его установить на 0, то получал еще больше ошибок Улыбающийся

Всем спасибо, тему можно закрывать Подмигивающий



« Последнее редактирование: Август 06, 2009, 10:31 от XpycT » Записан
spirit
Гость
« Ответ #13 : Август 06, 2009, 12:11 »

так может ты выложишь солюшен на вики?  Улыбающийся
Записан
XpycT
Гость
« Ответ #14 : Август 06, 2009, 13:06 »

так может ты выложишь солюшен на вики?  Улыбающийся

Даже не знаю Улыбающийся Дело в том что у меня в установленных библиотеках заблудиться можно..а в друг что упустил. Бедный юзверь прочитает солюшен, а собрать не сможет..и обидится на wiki  Смеющийся Хотя возможно посже и распишу поподробнее, будет и мне заметка на будущее Улыбающийся
Записан
Страниц: [1] 2 3   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.302 секунд. Запросов: 21.