aria2/src/util.h

950 lines
27 KiB
C
Raw Normal View History

2006-02-17 13:35:04 +00:00
/* <!-- copyright */
/*
* aria2 - The high speed download utility
2006-02-17 13:35:04 +00:00
*
* Copyright (C) 2006 Tatsuhiro Tsujikawa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
2006-02-17 13:35:04 +00:00
*/
/* copyright --> */
#ifndef D_UTIL_H
#define D_UTIL_H
2006-02-17 13:35:04 +00:00
#include "common.h"
#include <sys/time.h>
#include <limits.h>
#include <stdint.h>
#include <cstdio>
#include <string>
2006-02-17 13:35:04 +00:00
#include <utility>
#include <iosfwd>
2009-06-28 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net> Rewritten DownloadContext and removed SingleFileDownloadContext and BtContext and its derived classes. BitTorrent specific attributes are now set by DownloadContext::setAttribute() with key bittorrent::BITTORRENT. * src/AbstractBtMessage.cc * src/AbstractBtMessage.h * src/AbstractCommand.cc * src/AbstractCommand.h * src/AbstractProxyRequestCommand.cc * src/AbstractProxyResponseCommand.cc * src/ActivePeerConnectionCommand.cc * src/ActivePeerConnectionCommand.h * src/AnnounceList.cc * src/BtCheckIntegrityEntry.cc * src/BtConstants.h * src/BtContext.h: Removed * src/BtDependency.cc * src/BtExtendedMessage.cc * src/BtPieceMessage.cc * src/BtPieceMessage.h * src/BtPostDownloadHandler.cc * src/BtRegistry.cc * src/BtRegistry.h * src/BtSetup.cc * src/CheckIntegrityCommand.cc * src/CheckIntegrityEntry.cc * src/ChecksumCheckIntegrityEntry.cc * src/ConsoleStatCalc.cc * src/ContentTypeRequestGroupCriteria.cc * src/DHTGetPeersCommand.cc * src/DHTGetPeersCommand.h * src/DHTPeerLookupTask.cc * src/DHTPeerLookupTask.h * src/DHTTaskFactory.h * src/DHTTaskFactoryImpl.cc * src/DHTTaskFactoryImpl.h * src/DefaultBtAnnounce.cc * src/DefaultBtAnnounce.h * src/DefaultBtContext.cc: Removed * src/DefaultBtContext.h: Removed * src/DefaultBtInteractive.cc * src/DefaultBtInteractive.h * src/DefaultBtMessageDispatcher.cc * src/DefaultBtMessageDispatcher.h * src/DefaultBtMessageFactory.cc * src/DefaultBtMessageFactory.h * src/DefaultBtMessageReceiver.cc * src/DefaultBtMessageReceiver.h * src/DefaultBtProgressInfoFile.cc * src/DefaultBtRequestFactory.cc * src/DefaultBtRequestFactory.h * src/DefaultExtensionMessageFactory.cc * src/DefaultExtensionMessageFactory.h * src/DefaultPeerStorage.cc * src/DefaultPeerStorage.h * src/DefaultPieceStorage.cc * src/DefaultSegmentManFactory.cc * src/DiskAdaptor.cc * src/DiskAdaptor.h * src/DownloadContext.cc * src/DownloadContext.h * src/DownloadEngine.cc * src/DownloadEngineFactory.cc * src/DownloadHandler.cc * src/DownloadResult.h * src/FileAllocationCommand.cc * src/FileAllocationDispatcherCommand.cc * src/FileAllocationEntry.cc * src/FileEntry.h * src/FillRequestGroupCommand.cc * src/FtpDownloadCommand.cc * src/FtpFinishDownloadCommand.cc * src/FtpInitiateConnectionCommand.cc * src/FtpNegotiationCommand.cc * src/FtpTunnelRequestCommand.cc * src/FtpTunnelResponseCommand.cc * src/HandshakeExtensionMessage.cc * src/HandshakeExtensionMessage.h * src/HaveEraseCommand.cc * src/HttpDownloadCommand.cc * src/HttpInitiateConnectionCommand.cc * src/HttpProxyRequestCommand.cc * src/HttpProxyResponseCommand.cc * src/HttpRequest.cc * src/HttpRequest.h * src/HttpRequestCommand.cc * src/HttpResponseCommand.cc * src/HttpServerBodyCommand.cc * src/HttpServerCommand.cc * src/HttpSkipResponseCommand.cc * src/InitiateConnectionCommandFactory.cc * src/InitiatorMSEHandshakeCommand.cc * src/InitiatorMSEHandshakeCommand.h * src/IteratableChecksumValidator.cc * src/IteratableChecksumValidator.h * src/IteratableChunkChecksumValidator.cc * src/MSEHandshake.cc * src/MSEHandshake.h * src/Makefile.am * src/Makefile.in * src/Metalink2RequestGroup.cc * src/MetalinkPostDownloadHandler.cc * src/MultiDiskAdaptor.cc * src/MultiDiskAdaptor.h * src/MultiFileAllocationIterator.cc * src/MultiUrlRequestInfo.cc * src/PeerChokeCommand.cc * src/PeerChokeCommand.h * src/PeerInitiateConnectionCommand.cc * src/PeerInitiateConnectionCommand.h * src/PeerInteractionCommand.cc * src/PeerInteractionCommand.h * src/PeerReceiveHandshakeCommand.cc * src/PieceHashCheckIntegrityEntry.cc * src/RealtimeCommand.cc * src/ReceiverMSEHandshakeCommand.cc * src/RequestGroup.cc * src/RequestGroup.h * src/RequestGroupEntry.cc * src/RequestGroupMan.cc * src/SeedCheckCommand.cc * src/SeedCheckCommand.h * src/SegmentMan.cc * src/ShareRatioSeedCriteria.h * src/SingleFileDownloadContext.cc: Removed * src/SingleFileDownloadContext.h: Removed * src/SleepCommand.cc * src/StreamCheckIntegrityEntry.cc * src/TrackerWatcherCommand.cc * src/TrackerWatcherCommand.h * src/UnknownLengthPieceStorage.cc * src/Util.cc * src/Util.h * src/XmlRpcMethodImpl.cc * src/bittorrent_helper.cc * src/bittorrent_helper.h * src/download_helper.cc * src/main.cc * src/option_processing.cc * test/BitfieldManTest.cc * test/BittorrentHelperTest.cc * test/BtCancelMessageTest.cc * test/BtChokeMessageTest.cc * test/BtDependencyTest.cc * test/BtPieceMessageTest.cc * test/BtPostDownloadHandlerTest.cc * test/BtRegistryTest.cc * test/BtRejectMessageTest.cc * test/BtRequestMessageTest.cc * test/DHTPeerAnnounceStorageTest.cc * test/DefaultBtAnnounceTest.cc * test/DefaultBtContextTest.cc: Removed * test/DefaultBtMessageDispatcherTest.cc * test/DefaultBtMessageFactoryTest.cc * test/DefaultBtProgressInfoFileTest.cc * test/DefaultBtRequestFactoryTest.cc * test/DefaultExtensionMessageFactoryTest.cc * test/DefaultPeerStorageTest.cc * test/DefaultPieceStorageTest.cc * test/DirectDiskAdaptorTest.cc * test/DownloadContextTest.cc * test/DownloadHandlerFactoryTest.cc * test/DownloadHelperTest.cc * test/HandshakeExtensionMessageTest.cc * test/HttpRequestTest.cc * test/HttpResponseTest.cc * test/IteratableChecksumValidatorTest.cc * test/IteratableChunkChecksumValidatorTest.cc * test/MSEHandshakeTest.cc * test/Makefile.am * test/Makefile.in * test/Metalink2RequestGroupTest.cc * test/MetalinkPostDownloadHandlerTest.cc * test/MockBtContext.h: Removed * test/MockDHTTaskFactory.h * test/MockDownloadContext.h: Removed * test/MockPieceStorage.h * test/MultiDiskAdaptorTest.cc * test/MultiFileAllocationIteratorTest.cc * test/RequestGroupManTest.cc * test/RequestGroupTest.cc * test/SegmentManTest.cc * test/ShareRatioSeedCriteriaTest.cc * test/SingleFileDownloadContextTest.cc: Removed * test/UtilTest.cc * test/XmlRpcMethodTest.cc
2009-06-28 10:37:15 +00:00
#include <ostream>
#include <numeric>
#include <map>
2009-06-28 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net> Rewritten DownloadContext and removed SingleFileDownloadContext and BtContext and its derived classes. BitTorrent specific attributes are now set by DownloadContext::setAttribute() with key bittorrent::BITTORRENT. * src/AbstractBtMessage.cc * src/AbstractBtMessage.h * src/AbstractCommand.cc * src/AbstractCommand.h * src/AbstractProxyRequestCommand.cc * src/AbstractProxyResponseCommand.cc * src/ActivePeerConnectionCommand.cc * src/ActivePeerConnectionCommand.h * src/AnnounceList.cc * src/BtCheckIntegrityEntry.cc * src/BtConstants.h * src/BtContext.h: Removed * src/BtDependency.cc * src/BtExtendedMessage.cc * src/BtPieceMessage.cc * src/BtPieceMessage.h * src/BtPostDownloadHandler.cc * src/BtRegistry.cc * src/BtRegistry.h * src/BtSetup.cc * src/CheckIntegrityCommand.cc * src/CheckIntegrityEntry.cc * src/ChecksumCheckIntegrityEntry.cc * src/ConsoleStatCalc.cc * src/ContentTypeRequestGroupCriteria.cc * src/DHTGetPeersCommand.cc * src/DHTGetPeersCommand.h * src/DHTPeerLookupTask.cc * src/DHTPeerLookupTask.h * src/DHTTaskFactory.h * src/DHTTaskFactoryImpl.cc * src/DHTTaskFactoryImpl.h * src/DefaultBtAnnounce.cc * src/DefaultBtAnnounce.h * src/DefaultBtContext.cc: Removed * src/DefaultBtContext.h: Removed * src/DefaultBtInteractive.cc * src/DefaultBtInteractive.h * src/DefaultBtMessageDispatcher.cc * src/DefaultBtMessageDispatcher.h * src/DefaultBtMessageFactory.cc * src/DefaultBtMessageFactory.h * src/DefaultBtMessageReceiver.cc * src/DefaultBtMessageReceiver.h * src/DefaultBtProgressInfoFile.cc * src/DefaultBtRequestFactory.cc * src/DefaultBtRequestFactory.h * src/DefaultExtensionMessageFactory.cc * src/DefaultExtensionMessageFactory.h * src/DefaultPeerStorage.cc * src/DefaultPeerStorage.h * src/DefaultPieceStorage.cc * src/DefaultSegmentManFactory.cc * src/DiskAdaptor.cc * src/DiskAdaptor.h * src/DownloadContext.cc * src/DownloadContext.h * src/DownloadEngine.cc * src/DownloadEngineFactory.cc * src/DownloadHandler.cc * src/DownloadResult.h * src/FileAllocationCommand.cc * src/FileAllocationDispatcherCommand.cc * src/FileAllocationEntry.cc * src/FileEntry.h * src/FillRequestGroupCommand.cc * src/FtpDownloadCommand.cc * src/FtpFinishDownloadCommand.cc * src/FtpInitiateConnectionCommand.cc * src/FtpNegotiationCommand.cc * src/FtpTunnelRequestCommand.cc * src/FtpTunnelResponseCommand.cc * src/HandshakeExtensionMessage.cc * src/HandshakeExtensionMessage.h * src/HaveEraseCommand.cc * src/HttpDownloadCommand.cc * src/HttpInitiateConnectionCommand.cc * src/HttpProxyRequestCommand.cc * src/HttpProxyResponseCommand.cc * src/HttpRequest.cc * src/HttpRequest.h * src/HttpRequestCommand.cc * src/HttpResponseCommand.cc * src/HttpServerBodyCommand.cc * src/HttpServerCommand.cc * src/HttpSkipResponseCommand.cc * src/InitiateConnectionCommandFactory.cc * src/InitiatorMSEHandshakeCommand.cc * src/InitiatorMSEHandshakeCommand.h * src/IteratableChecksumValidator.cc * src/IteratableChecksumValidator.h * src/IteratableChunkChecksumValidator.cc * src/MSEHandshake.cc * src/MSEHandshake.h * src/Makefile.am * src/Makefile.in * src/Metalink2RequestGroup.cc * src/MetalinkPostDownloadHandler.cc * src/MultiDiskAdaptor.cc * src/MultiDiskAdaptor.h * src/MultiFileAllocationIterator.cc * src/MultiUrlRequestInfo.cc * src/PeerChokeCommand.cc * src/PeerChokeCommand.h * src/PeerInitiateConnectionCommand.cc * src/PeerInitiateConnectionCommand.h * src/PeerInteractionCommand.cc * src/PeerInteractionCommand.h * src/PeerReceiveHandshakeCommand.cc * src/PieceHashCheckIntegrityEntry.cc * src/RealtimeCommand.cc * src/ReceiverMSEHandshakeCommand.cc * src/RequestGroup.cc * src/RequestGroup.h * src/RequestGroupEntry.cc * src/RequestGroupMan.cc * src/SeedCheckCommand.cc * src/SeedCheckCommand.h * src/SegmentMan.cc * src/ShareRatioSeedCriteria.h * src/SingleFileDownloadContext.cc: Removed * src/SingleFileDownloadContext.h: Removed * src/SleepCommand.cc * src/StreamCheckIntegrityEntry.cc * src/TrackerWatcherCommand.cc * src/TrackerWatcherCommand.h * src/UnknownLengthPieceStorage.cc * src/Util.cc * src/Util.h * src/XmlRpcMethodImpl.cc * src/bittorrent_helper.cc * src/bittorrent_helper.h * src/download_helper.cc * src/main.cc * src/option_processing.cc * test/BitfieldManTest.cc * test/BittorrentHelperTest.cc * test/BtCancelMessageTest.cc * test/BtChokeMessageTest.cc * test/BtDependencyTest.cc * test/BtPieceMessageTest.cc * test/BtPostDownloadHandlerTest.cc * test/BtRegistryTest.cc * test/BtRejectMessageTest.cc * test/BtRequestMessageTest.cc * test/DHTPeerAnnounceStorageTest.cc * test/DefaultBtAnnounceTest.cc * test/DefaultBtContextTest.cc: Removed * test/DefaultBtMessageDispatcherTest.cc * test/DefaultBtMessageFactoryTest.cc * test/DefaultBtProgressInfoFileTest.cc * test/DefaultBtRequestFactoryTest.cc * test/DefaultExtensionMessageFactoryTest.cc * test/DefaultPeerStorageTest.cc * test/DefaultPieceStorageTest.cc * test/DirectDiskAdaptorTest.cc * test/DownloadContextTest.cc * test/DownloadHandlerFactoryTest.cc * test/DownloadHelperTest.cc * test/HandshakeExtensionMessageTest.cc * test/HttpRequestTest.cc * test/HttpResponseTest.cc * test/IteratableChecksumValidatorTest.cc * test/IteratableChunkChecksumValidatorTest.cc * test/MSEHandshakeTest.cc * test/Makefile.am * test/Makefile.in * test/Metalink2RequestGroupTest.cc * test/MetalinkPostDownloadHandlerTest.cc * test/MockBtContext.h: Removed * test/MockDHTTaskFactory.h * test/MockDownloadContext.h: Removed * test/MockPieceStorage.h * test/MultiDiskAdaptorTest.cc * test/MultiFileAllocationIteratorTest.cc * test/RequestGroupManTest.cc * test/RequestGroupTest.cc * test/SegmentManTest.cc * test/ShareRatioSeedCriteriaTest.cc * test/SingleFileDownloadContextTest.cc: Removed * test/UtilTest.cc * test/XmlRpcMethodTest.cc
2009-06-28 10:37:15 +00:00
#include <iomanip>
#include <algorithm>
#include <vector>
#include "SharedHandle.h"
#include "a2time.h"
#include "a2netcompat.h"
#include "a2functional.h"
#include "SegList.h"
#include "a2iterator.h"
#include "message.h"
#include "DlAbortEx.h"
#include "fmt.h"
namespace aria2 {
2006-02-17 13:35:04 +00:00
class Randomizer;
class BitfieldMan;
2007-11-27 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> Rewritten to add content-type support. * src/DownloadHandler.{h, cc} * src/BtPostDownloadHandler.{h, cc} * test/BtPostDownloadHandlerTest.cc * src/MetalinkPostDownloadHandler.{h, cc} * test/MetalinkPostDownloadHandlerTest.cc * src/PostDownloadHandler.{h, cc} * src/DownloadHandlerConstants.{h, cc} * src/RequestGroup.cc * src/HttpResponseCommand.cc * src/FtpNegotiationCommand.cc * src/SingleFileDownloadContext.{h, cc} * src/RequestGroup.h * src/RequestGroupCriteria.h * src/ContentTypeRequestGroupCriteria.h Added 'mem' option value for --follow-metalink, --follow-torrent. If it is give, metalink/torrent file is not written to the disk, but just is kept in memory. Parsing is occurred on memory. * src/MetalinkHelper.{h, cc} * src/MetalinkProcessor.h * src/Xml2MetalinkProcessor.{h, cc} * test/Xml2MetalinkProcessorTest.cc * src/DownloadHandlerFactory.{h, cc} * test/DownloadHandlerFactoryTest.cc * src/PreDownloadHandler.{h, cc} * src/OptionHandlerFactory.cc * src/DefaultBtContext.{h, cc} * test/DefaultBtContextTest.cc * src/version_usage.cc * src/Metalink2RequestGroup.{h, cc} * src/RequestGroup.{h, cc} * src/a2functional.h * test/a2functionalTest.cc * src/MemoryBufferPreDownloadHandler.{h, cc} * src/OptionHandlerImpl.h * src/prefs.h * src/Util.{h, cc} * test/UtilTest.cc Keep DownloadResult rather than RequestGroup after downloads to reduce memory usage. * src/RequestGroupMan.{h, cc} * src/DownloadEngine.cc * src/BtDependency.{h, cc}: Changed the type of dependee from WeakHandle to SharedHandle because WeakHandle could be null. * src/RequestGroup.{h, cc} * src/DownloadEngineFactory.cc * src/DownloadResult.h Set totalLength after download finished * src/UnknownLengthPieceStorage.{h, cc} Keep torrent file specified in metalink in memory. * src/Metalink2RequestGroup.cc * src/BtDependency.cc * src/TrueRequestGroupCriteria.h Fixed the bug: seekg is used where seekp should be used. * src/ByteArrayDiskWriter.cc * test/ByteArraydiskWriterTest.cc
2007-11-27 12:27:10 +00:00
class BinaryStream;
class FileEntry;
class RequestGroup;
class Option;
class Pref;
#define STRTOLL(X) strtoll(X, reinterpret_cast<char**>(0), 10)
#define STRTOULL(X) strtoull(X, reinterpret_cast<char**>(0), 10)
#define START_INDEX(OFFSET, PIECE_LENGTH) ((OFFSET)/(PIECE_LENGTH))
#define END_INDEX(OFFSET, LENGTH, PIECE_LENGTH) (((OFFSET)+(LENGTH)-1)/(PIECE_LENGTH))
2006-02-17 13:35:04 +00:00
#define DIV_FLOOR(X,Y) ((X)/(Y)+((X)%(Y)? 1:0))
#ifdef WORDS_BIGENDIAN
inline uint64_t ntoh64(uint64_t x) { return x; }
inline uint64_t hton64(uint64_t x) { return x; }
#else // !WORDS_BIGENDIAN
inline uint64_t byteswap64(uint64_t x) {
uint64_t v1 = ntohl(x & 0x00000000ffffffffllu);
uint64_t v2 = ntohl(x >> 32);
return (v1 << 32)|v2;
}
inline uint64_t ntoh64(uint64_t x) { return byteswap64(x); }
inline uint64_t hton64(uint64_t x) { return byteswap64(x); }
#endif // !WORDS_BIGENDIAN
#ifdef __MINGW32__
std::wstring utf8ToWChar(const std::string& src);
std::wstring utf8ToWChar(const char* str);
std::string utf8ToNative(const std::string& src);
std::string wCharToUtf8(const std::wstring& wsrc);
std::string nativeToUtf8(const std::string& src);
#else // !__MINGW32__
# define utf8ToWChar(src) src
# define utf8ToNative(src) src
#endif // !__MINGW32__
namespace util {
template<typename InputIterator>
void divide
2011-11-05 03:01:57 +00:00
(std::pair<std::pair<InputIterator, InputIterator>,
std::pair<InputIterator, InputIterator> >& hp,
InputIterator first,
InputIterator last,
char delim)
{
InputIterator dpos = std::find(first, last, delim);
if(dpos == last) {
hp.first = stripIter(first, last);
hp.second.first = hp.second.second;
} else {
hp.first = stripIter(first, dpos);
hp.second = stripIter(dpos+1, last);
}
}
template<typename T>
std::string uitos(T value, bool comma = false)
{
std::string str;
if(value == 0) {
str = "0";
return str;
}
unsigned int count = 0;
while(value) {
++count;
char digit = value%10+'0';
if(comma && count > 3 && count%3 == 1) {
str += ',';
}
str += digit;
value /= 10;
}
std::reverse(str.begin(), str.end());
return str;
}
std::string itos(int64_t value, bool comma = false);
2006-12-24 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> Rewritten a portion of bittorrent implementation: * src/BtMessageValidator.h: New class. * src/BtBitfieldMessageValidator.h: New class. * src/BtHandshakeMessageValidator.h: New class. * src/BtRequestMessageValidator.h: New class. * src/BtSuggestPieceMessageValidator.h: New class. * src/BtAllowedFastMessageValidator.h: New class. * src/BtRejectMessageValidator.h: New class. * src/BtCancelMessageValidator.h: New class. * src/BtPieceMessageValidator.h: New class. * src/BtHaveMessageValidator.h: New class. * src/BtEventListener.h: New class. * src/AbstractBtEventListener.h: New class. * src/BtEvent.h: New class. * src/BtChokingEvent.h: New class. * src/BtChokedEvent.h: New class. * src/BtCancelSendingPieceEvent.h: New class. * src/BtAbortOutstandingRequestEvent.h: New class. * src/Randomizer.h: New class. * src/SimpleRandomizer.h: New class. * src/BtMessage.h: New class. * src/AbstractBtMessage.h: New class. * src/SimpleBtMessage.h: New class. * src/BtHaveMessage.h: New class. * src/BtInterestedMessage.h: New class. * src/BtAllowedFastMessage.h: New class. * src/BtUnchokeMessage.h: New class. * src/BtCancelMessage.h: New class. * src/BtNotInterestedMessage.h: New class. * src/BtChokeMessage.h: New class. * src/BtHaveNoneMessage.h: New class. * src/BtHandshakeMessage.h: New class. * src/BtSuggestPieceMessage.h: New class. * src/BtHaveMessage.h: New class. * src/BtPieceMessage.h: New class. * src/BtHaveAllMessage.h: New class. * src/BtKeepAliveMessage.h: New class. * src/BtPortMessage.h: New class. * src/BtRejectMessage.h: New class. * src/BtBitfieldMessage.h: New class. * src/BtRequestMessage.h: New class. * src/DefaultBtRequestFactory.h: New class. * src/DefaultBtMessageReceiver.h: New class. * src/BtInteractive.h: New class. * src/BtMessageDispatcher.h: New class. * src/DefaultBtMessageDispatcher.h: New class. * src/DefaultBtInteractive.h: New class. * src/BitfieldManFactory.h: New class. * src/HandleRegistry.h: New class. * src/BtMessageFactory.h: New class. * src/BtMessageReceiver.h: New class. * src/DefaultBtMessageFactory.h: New class. * src/PeerObject.h: New class. * src/BtRequestFactory.h: New class.
2006-12-24 06:25:21 +00:00
/**
* Computes difference in micro-seconds between tv1 and tv2,
* assuming tv1 is newer than tv2.
* If tv1 is older than tv2, then this method returns 0.
*/
int64_t difftv(struct timeval tv1, struct timeval tv2);
int32_t difftvsec(struct timeval tv1, struct timeval tv2);
extern const std::string DEFAULT_STRIP_CHARSET;
2006-02-21 12:27:17 +00:00
template<typename InputIterator>
std::pair<InputIterator, InputIterator> stripIter
(InputIterator first, InputIterator last,
const std::string& chars = DEFAULT_STRIP_CHARSET)
{
for(; first != last &&
std::find(chars.begin(), chars.end(), *first) != chars.end(); ++first);
if(first == last) {
return std::make_pair(first, last);
}
InputIterator left = last-1;
for(; left != first &&
std::find(chars.begin(), chars.end(), *left) != chars.end(); --left);
return std::make_pair(first, left+1);
}
template<typename InputIterator>
InputIterator lstripIter
(InputIterator first, InputIterator last, char ch)
{
for(; first != last && *first == ch; ++first);
return first;
}
template<typename InputIterator, typename InputIterator2>
InputIterator lstripIter
(InputIterator first, InputIterator last,
InputIterator2 cfirst, InputIterator2 clast)
{
for(; first != last && std::find(cfirst, clast, *first) != clast; ++first);
return first;
}
template<typename InputIterator>
InputIterator lstripIter
(InputIterator first, InputIterator last)
{
return lstripIter(first, last,
DEFAULT_STRIP_CHARSET.begin(), DEFAULT_STRIP_CHARSET.end());
}
std::string strip
(const std::string& str, const std::string& chars = DEFAULT_STRIP_CHARSET);
std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr);
2006-03-21 14:12:51 +00:00
std::string percentEncode(const unsigned char* target, size_t len);
2006-03-21 14:12:51 +00:00
std::string percentEncode(const std::string& target);
2007-03-15 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To handle Segment as SegmentHandle: * src/AbstractCommand.cc (execute): Rewritten. * src/SegmentMan.h: Segment -> SegmentHandle Introducded HttpResponse class, HttpRequest class to improve code extensiveness and make it clear: * src/HttpDownloadCommand.cc: transfer encoders are now managed by HttpResponse class. * src/HttpRequest.h, src/HttpRequest.cc: New class. * src/HttpResponse.h, src/HttpResponse.cc: New class. * src/HttpConnection.cc: Contruction of http request were moved to HttpRequest class. * src/HttpResponseCommand.h, src/HttpResponseCommand.cc: Refactored. * src/HttpRequestCommand.cc (executeInternal): Rewritten. * src/HttpAuthConfig.h: New class. * src/Range.h: New class. To make FtpTunnel{Request, Response}Command and HttpProxy{Request, Response}Command derived from AbstractProxy{Request, Response}Command: * src/FtpTunnelResponseCommand.h, src/FtpTunnelResponseCommand.cc: Derived from AbstractProxyRequestCommand class. * src/FtpTunnelRequestCommand.h, src/FtpTunnelRequestCommand.cc: Derived from AbstractProxyResponseCommand class. * src/HttpProxyRequestCommand.h, src/HttpProxyRequestCommand.cc: Derived from AbstractProxyRequestCommand class. * src/HttpProxyResponseCommand.h, src/HttpProxyResponseCommand.cc: Derived from AbstractProxyResponseCommand class. * src/AbstractProxyRequestCommand.h, src/AbstractProxyRequestCommand.cc : New class. * src/AbstractProxyResponseCommand.h, src/AbstractProxyResponseCommand.cc: New class. To add netrc support: * src/Netrc.h, src/Netrc.cc: New class. * src/Util.h, src/Util.cc (split): New function. * src/HttpHeader.cc (getRange): Fixed so that it inspects "Content-Range" header instead of "Range" header. * src/HttpHeader.h (getStatus): Removed. (setStatus): Removed. * src/Segment.h (getPositionToWrite): New function.
2007-03-15 15:07:18 +00:00
std::string percentEncodeMini(const std::string& target);
bool inRFC3986ReservedChars(const char c);
bool inRFC3986UnreservedChars(const char c);
bool isUtf8(const std::string& str);
std::string percentDecode
(std::string::const_iterator first, std::string::const_iterator last);
std::string torrentPercentEncode(const unsigned char* target, size_t len);
std::string torrentPercentEncode(const std::string& target);
std::string toHex(const unsigned char* src, size_t len);
2006-03-21 14:12:51 +00:00
std::string toHex(const char* src, size_t len);
std::string toHex(const std::string& src);
unsigned int hexCharToUInt(unsigned char ch);
// Converts hexadecimal ascii characters in [first, last) into packed
// binary form and return the result. If characters in given range is
// not well formed, then empty string is returned.
template<typename InputIterator>
std::string fromHex(InputIterator first, InputIterator last)
{
std::string dest;
size_t len = last-first;
if(len%2) {
return dest;
}
for(; first != last; first += 2) {
unsigned char high = hexCharToUInt(*first);
unsigned char low = hexCharToUInt(*(first+1));
if(high == 255 || low == 255) {
dest.clear();
return dest;
}
dest += (high*16+low);
}
return dest;
}
FILE* openFile(const std::string& filename, const std::string& mode);
2006-03-21 14:12:51 +00:00
bool isPowerOf(int num, int base);
2006-04-06 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To print ETA: * src/TorrentDownloadEngine.cc (afterEachIteration): Added download completion handling when dealing with TorrentMan::isPartialDownloadingMode() == true. * src/TorrentDownloadEngine.h (onPartialDownloadingCompletes): New function. * src/TorrentConsoleDownloadEngine.h (startup): New variable. (sessionDownloadLength): New variable. (avgSpeed): New variable. (eta): New variable. * src/TorrentConsoleDownloadEngine.cc (initStatistics): Initialized new variables: eta, avgSpeed, startup. (calculateSpeed): Calculate average speed and ETA. (printStatistics): Added ETA. * src/Util.h (secfmt): New function. * src/Util.cc (secfmt): New function. 2006-04-05 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To detect "keep alive" flooding: * src/PeerInteractionCommand.h (keepAliveCount): New variable * src/PeerInteractionCommand.cc (Constructor): Initialized new variable: keepAliveCount. (detectMessageFlooding): Added "keep alive" flooding detection. (receiveMessage): Increase keepAliveCount when "keep alive" message received. To add the ability to download only specified files in multi-file torrent: * src/BitfieldMan.h (filterBitfield): New variable. (filterEnabled): New variable. (setFilterBit): New function. (enableFilter): New function. (disableFilter): New function. (isFilterEnabled): New function. (getFilteredTotalLength): New function. (getCompletedLength): New function. * src/BitfieldMan.cc (Constructor): Initialized new variable: filterBitfield, filterEnabled. (CopyConstructor): Added filterBitfield and filterEnabled. (operator==): Added filterBitfield and filterEnabled. (Destructor): Added filterBitfield. (getMissingIndex): Use filterBitfield. (getMissingUnusedIndex): Use filterBitfield. (getFirstMissingUnusedIndex): Use filterBitfield. (getFirstMissingUnusedIndex): Use filterBitfield. (getAllMissingIndexes): Use filterBitfield. (countMissingBlock): Use filterBitfield. (countBlock): Use filterBitfield. (setBitInternal): Added new argument on. (setUseBit): Use setBitInternal. (unsetUseBit): Use setBitInternal. (setBit): Use setBitInternal. (unsetBit): Use setBitInternal. (isAllBitSet): Use filterBitfield. (setFilterBit): New function. (addFilter): New function. (enableFilter): New function. (disableFilter): New function. (clearFilter): New function. (isFilterEnabled): New function. (getFilteredTotalLength): New function. (getCompletedLength): New function. * src/TorrentMan.h [FileEntry](Constructor): Updated signature. Initalized newly added variables. [FileEntry](offset): New variable. [FileEntry](extracted): New variable. [FileEntry](requested): New variable. (readFileEntry): New function. (option): New variable. (splitMultiFile): Removed const qualifier. (fixFilename): Removed const qualifier. (readFileEntryFromMetaInfoFile): New function. (finishPartialDownloadingMode): New function. (isPartialDownloadingMode): New function. (setFileEntriesToDownload): New function. (getCompletedLength): New function. (getPartialTotalLength): New function. * src/TorrentMan.cc (readFileEntry): New function. (setup): Use readFileEntry. If no-preallocation option is specified, use DefaultDiskWriter. (readFileEntryFromMetaInfoFile): New function. (fixFilename): Removed const qualifier. (splitMultiFile): Removed const qualifier. (setFileEntriesToDownload): New function. (isPartialDownloadingMode): New function. (finishPartialDownloadingMode): New function. (getCompletedLength): New function. (getPartialTotalLength): New function. * src/TorrentConsoleDownloadEngine.h (partialDownloadLengthDiff): New variable. (partialTotalLength): New variable. (downloadLength): New variable. (totalLength): New variable. * src/TorrentConsoleDownloadEngine.cc (onPartialDownloadingCompletes): Added log. (initStatistics): Initialized new variables: partialDownloadLengthDiff, partialTotalLength, downloadLength, totalLength. (calculate): Calculate downloadLength and totalLength. * src/prefs.h :New definition PREF_NO_PREALLOCATION * src/main.cc (addCommand): Changed argument signature. (main): Added new variable: args. Added new option "torrent-show-files" "no-preallocation". Usage is not updated yet. 2006-04-02 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> * src/PeerMessage.cc (setBitfield): Fixed invalid memory de-allocation.
2006-04-06 12:52:16 +00:00
std::string secfmt(time_t sec);
To add TrackerUpdateCommand with which replaces CompactTrackerResponseProcessor: * src/TrackerWatcherCommand.h (req): Removed. * src/TrackerWatcherCommand.cc (execute): Send a request to tracker if the number of peer connections are less than 30. * src/ByteArrayDiskWriter.h (readData): Implemented. * src/SegmentMan.h (diskWriter): New function. * src/SegmentMan.cc (init): Added a call to diskWriter->closeFile() * src/main.cc : Removed #include "CompactTrackerResponseProcessor.h" (main): Use TrackerUpdateCommand. * src/TorrentMan.h (CompactTrackerResponseProcessor): Removed. (req): New variable. (setTrackerResponseProcessor): Removed. (getTrackerResponseProcessor): Removed. (processTrackerResponse): Removed. * src/DownloadEngine.h (diskWriter): Removed. * src/TorrentDownloadEngine.cc (afterEachIteration): Removed a call to torrentMan->processTrackerResponse(). To add Util::expandBuffer: * src/ByteArrayDiskWriter.h (expandBuffer): Removed. * src/ByteArrayDiskWriter.cc (writeData): Use Util::expandBuffer(). * src/Util.h (expandBuffer): New function. To fix the bug that causes segmentation fault when "-l ." is specified in command-line option: * src/SimpleLogger.h (SimpleLogger): Removed "filename" argument. (openFile): New function. (closeFile): New function. * src/SimpleLogger.cc (SimpleLogger): Removed fopen. (~SimpleLogger): Call closeFile(); * src/LogFactory.cc (getInstance): Added a call to slogger->openFile(). * src/main.cc (main): Added a check to see logger is configured properly. To enable HTTP authentication without specifying "--http-auth-scheme" * src/prefs.h (PREF_HTTP_AUTH_ENABLED): New definition. * src/HttpConnection.cc (createRequest): Send Authorization header if PREF_HTTP_AUTH_ENABLED == V_TRUE. * src/main.cc (main): Preset PREF_HTTP_AUTH_SCHEME to V_TRUE If "--http-user" is specified, set PREF_HTTP_AUTH_ENABLED to V_TRUE * src/Peer.cc (shouldChoke): Updated algorithm. * src/message.h (EX_AUTH_FAILED): New definition. (EX_FILE_OPEN): New definition. * src/HttpResponseCommand.cc (checkResponse): Throw DlAbortEx if status == 401. (handleDefaultEncoding): Added a call to diskWriter->initAndOpenFile() if req->isTorrent == true. * src/main.cc (handler): Removed the check to see e->diskWriter != NULL (torrentHandler): Removed the check to see diskAdaptor != NULL. * src/AbstractDiskWriter.cc (openExistingFile): Updated messsage. (createFile): Updated message.
2006-04-19 17:23:58 +00:00
template<typename InputIterator>
bool parseIntNoThrow
(int32_t& result, InputIterator first, InputIterator last, int base = 10)
{
// Without strip, strtol(" -1 ",..) emits error.
2011-11-05 03:01:57 +00:00
std::pair<InputIterator, InputIterator> p = util::stripIter(first, last);
if(p.first == p.second) {
return false;
}
char buf[32];
size_t len = std::distance(p.first, p.second);
if(len+1 > sizeof(buf)) {
return false;
}
std::copy(p.first, p.second, &buf[0]);
buf[len] = '\0';
char* stop;
errno = 0;
long int v = strtol(buf, &stop, base);
if(*stop != '\0') {
return false;
} else if(((v == LONG_MAX || v == LONG_MIN) && (errno == ERANGE)) ||
v < INT32_MIN || INT32_MAX < v) {
return false;
}
result = v;
return true;
}
2007-11-20 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> Preallocate non-requested file which is adjacent forward to requested file('requested' files means the files given in --select-file option) if they share a same piece. This fixes long pause in the file system which doesn't support sparse files like FAT32 while downloading. * src/MultiFileAllocationIterator.{h, cc} * test/MultiFileAllocationIteratorTest.cc * src/FileEntry.{h, cc} Removed unused _option. * src/MultiDiskAdaptor.h * test/MultiDiskAdaptorTest.cc * src/DefaultPieceStorage.cc Set the default value of --seed-ratio to 1.0. If 0.0 is given, then seeding continues regardless of share ratio. * src/version_usage.cc * src/option_processing.cc * src/BtSetup.cc * doc/aria2c.1.txt * doc/aria2c.1 Fixed: Selective download is not working in BitTorrent * src/RequestGroup.cc Introduced Sequence class. Use this instead of Util::unfoldRange() * src/PieceStorage.h * test/MockPieceStorage.h * src/UnknownLengthPieceStorage.h * src/DefaultPieceStorage.{h, cc} * src/Metalink2RequestGroup.cc * src/RequestGroup.cc * src/Sequence.h * test/SequenceTest.cc * src/IntSequence.h * src/message.h * src/Util.{h, cc} * test/UtilTest.cc Added new function 'parse' to catch exception thrown by subclass's parseArg * src/OptionHandler.h * src/OptionParser.cc * src/NameMatchOptionHandler.h * src/OptionHandlerImpl.h * test/OptionHandlerTest.cc Added IntegerRangeOptionHandler. Used for --listen-port and --select-file. Now --listen-port accepts range of port. * src/OptionHandlerFactory.cc * src/version_usage.cc * src/OptionHandlerImpl.h * src/option_processing.cc * src/BtSetup.cc * src/PeerListenCommand.{h, cc} * doc/aria2c.1.txt * doc/aria2c.1 Implemented operator< for Exception class to provide easy way to print exception stack trace. * src/Exception.{h, cc} * src/main.cc * src/option_processing.cc
2007-11-21 16:14:40 +00:00
template<typename InputIterator>
bool parseUIntNoThrow
(uint32_t& result, InputIterator first, InputIterator last, int base = 10)
{
// Without strip, strtol(" -1 ",..) emits error.
2011-11-05 03:01:57 +00:00
std::pair<InputIterator, InputIterator> p = util::stripIter(first, last);
if(p.first == p.second) {
return false;
}
char buf[32];
size_t len = std::distance(p.first, p.second);
if(len+1 > sizeof(buf)) {
return false;
}
std::copy(p.first, p.second, &buf[0]);
buf[len] = '\0';
// We don't allow negative number.
if(buf[0] == '-') {
return false;
}
char* stop;
errno = 0;
unsigned long int v = strtoul(buf, &stop, base);
if(*stop != '\0') {
return false;
} else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) {
return false;
}
result = v;
return true;
}
template<typename InputIterator>
bool parseLLIntNoThrow
(int64_t& result, InputIterator first, InputIterator last, int base = 10)
{
// Without strip, strtol(" -1 ",..) emits error.
2011-11-05 03:01:57 +00:00
std::pair<InputIterator, InputIterator> p = util::stripIter(first, last);
if(p.first == p.second) {
return false;
}
char buf[32];
size_t len = std::distance(p.first, p.second);
if(len+1 > sizeof(buf)) {
return false;
}
std::copy(p.first, p.second, &buf[0]);
buf[len] = '\0';
char* stop;
errno = 0;
int64_t v = strtoll(buf, &stop, base);
if(*stop != '\0') {
return false;
} else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
return false;
}
result = v;
return true;
}
template<typename InputIterator>
int64_t parseLLInt(InputIterator first, InputIterator last, int base = 10)
{
2011-11-05 03:01:57 +00:00
std::pair<InputIterator, InputIterator> p = util::stripIter(first, last);
if(p.first == p.second) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"empty string"));
}
char buf[32];
size_t len = std::distance(p.first, p.second);
if(len+1 > sizeof(buf)) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"too large"));
}
std::copy(p.first, p.second, &buf[0]);
buf[len] = '\0';
char* stop;
errno = 0;
int64_t v = strtoll(buf, &stop, base);
if(*stop != '\0') {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
} else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
}
return v;
}
template<typename InputIterator>
int32_t parseInt(InputIterator first, InputIterator last, int base = 10)
{
int64_t v = util::parseLLInt(first, last, base);
if(v < INT32_MIN || INT32_MAX < v) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
std::string(first, last).c_str()));
}
return v;
}
2007-11-20 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> Preallocate non-requested file which is adjacent forward to requested file('requested' files means the files given in --select-file option) if they share a same piece. This fixes long pause in the file system which doesn't support sparse files like FAT32 while downloading. * src/MultiFileAllocationIterator.{h, cc} * test/MultiFileAllocationIteratorTest.cc * src/FileEntry.{h, cc} Removed unused _option. * src/MultiDiskAdaptor.h * test/MultiDiskAdaptorTest.cc * src/DefaultPieceStorage.cc Set the default value of --seed-ratio to 1.0. If 0.0 is given, then seeding continues regardless of share ratio. * src/version_usage.cc * src/option_processing.cc * src/BtSetup.cc * doc/aria2c.1.txt * doc/aria2c.1 Fixed: Selective download is not working in BitTorrent * src/RequestGroup.cc Introduced Sequence class. Use this instead of Util::unfoldRange() * src/PieceStorage.h * test/MockPieceStorage.h * src/UnknownLengthPieceStorage.h * src/DefaultPieceStorage.{h, cc} * src/Metalink2RequestGroup.cc * src/RequestGroup.cc * src/Sequence.h * test/SequenceTest.cc * src/IntSequence.h * src/message.h * src/Util.{h, cc} * test/UtilTest.cc Added new function 'parse' to catch exception thrown by subclass's parseArg * src/OptionHandler.h * src/OptionParser.cc * src/NameMatchOptionHandler.h * src/OptionHandlerImpl.h * test/OptionHandlerTest.cc Added IntegerRangeOptionHandler. Used for --listen-port and --select-file. Now --listen-port accepts range of port. * src/OptionHandlerFactory.cc * src/version_usage.cc * src/OptionHandlerImpl.h * src/option_processing.cc * src/BtSetup.cc * src/PeerListenCommand.{h, cc} * doc/aria2c.1.txt * doc/aria2c.1 Implemented operator< for Exception class to provide easy way to print exception stack trace. * src/Exception.{h, cc} * src/main.cc * src/option_processing.cc
2007-11-21 16:14:40 +00:00
template<typename InputIterator>
uint64_t parseULLInt(InputIterator first, InputIterator last, int base = 10)
{
2011-11-05 03:01:57 +00:00
std::pair<InputIterator, InputIterator> p = util::stripIter(first, last);
if(p.first == p.second) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"empty string"));
}
char buf[32];
size_t len = std::distance(p.first, p.second);
if(len+1 > sizeof(buf)) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"too large"));
}
std::copy(p.first, p.second, &buf[0]);
buf[len] = '\0';
// We don't allow negative number.
if(buf[0] == '-') {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
}
char* stop;
errno = 0;
uint64_t v = strtoull(buf, &stop, base);
if(*stop != '\0') {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
} else if((v == ULLONG_MAX) && (errno == ERANGE)) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
}
return v;
}
template<typename InputIterator>
uint32_t parseUInt(InputIterator first, InputIterator last, int base = 10)
{
uint64_t v = util::parseULLInt(first, last, base);
if(UINT32_MAX < v) {
throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
std::string(first, last).c_str()));
}
return v;
}
void parseIntSegments(SegList<int>& sgl, const std::string& src);
// Parses string which specifies the range of piece index for higher
// priority and appends those indexes into result. The input string
// src can contain 2 keywords "head" and "tail". To include both
// keywords, they must be separated by comma. "head" means the pieces
// where the first byte of each file sits. "tail" means the pieces
// where the last byte of each file sits. These keywords can take one
// parameter, SIZE. For example, if "head=SIZE" is specified, pieces
// in the range of first SIZE bytes of each file get higher
// priority. SIZE can include K or M(1K = 1024, 1M = 1024K).
// If SIZE is omitted, SIZE=defaultSize is used.
//
// sample: head=512K,tail=512K
void parsePrioritizePieceRange
(std::vector<size_t>& result, const std::string& src,
const std::vector<SharedHandle<FileEntry> >& fileEntries,
size_t pieceLength,
uint64_t defaultSize = 1048576 /* 1MiB */);
// Converts ISO/IEC 8859-1 string src to utf-8.
std::string iso8859ToUtf8(const std::string& src);
std::string getContentDispositionFilename(const std::string& header);
2006-05-18 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To remove a wait from download loop: * src/DownloadEngine.cc (run): Comment out shortSleep. To rewrite the message handling: * src/CancelMessage.h: Derived from SimplePeerMessage. (msg): New variable. (create): New function. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/CancelMessage.cc (create): New function. (receivedAction): Replaced deleteRequestMessageInQueue with rejectPieceMessageInQueue. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/BitfieldMessage.h: Derived from SimplePeerMessage. (msg): New variable. (msgLength): New variable. (~BitfieldMessage): Deleted msg. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/BitfieldMessage.cc (create): New function. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/ChokeMessage.h: Derived from SimplePeerMessage. (msg): New variable. (sendPredicate): New function. (onSendComplete): New function. (send): Removed. (getMessage): New function. (getMessageLength): New function. (create): New function. * src/ChokeMessage.cc (create): New function. (send): Removed. (sendPredicate): New function. (getMessage): New function. (getMessageLength): New function. (onSendComplete): New function. * src/KeepAliveMessage.h: Derived from SimplePeerMessage. (msg): New variable. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/KeepAliveMessage.cc (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/PortMessage.h (create): New function. (receivedAction): Updated log message. * src/PortMessage.cc: New file. * src/UnchokeMessage.h: Derived from SimplePeerMessage. (msg): New variable. (sendPredicate): New function. (onSendComplete): New function. (create): New function. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/UnchokeMessage.cc (create): New function. (send): Removed. (sendPredicate): New function. (getMessage): New function. (getMessageLength): New function. (onSendComplete): New function. * src/PieceMessage.h (leftPieceDataLength): Removed. (leftDataLength): New variable. (headerSend): New variable. (pendingCount): New variable. (msgHeader): New variable. (sendPieceData): New function. (incrementPendingCount): New function. (isPendingCountMax): New function. (create): New function. (getMessageHeader): New function. (getMessageHeaderLength): New function. * src/PieceMessage.cc (create): New function. (getMessageHeader): New function. (getMessageHeaderLength): New function. (send): Rewritten. (sendPieceData): New function. * src/HaveMessage.h: Derived from SimplePeerMessage. (msg): New variable. (create): New function. (getMessage): New function. (getMessageLength): New function. * src/HaveMessage.cc (create): New function. (send): Removed. (sendPieceData): New function. (getMessage): New function. (getMessageLength): New function. * src/RequestMessage.h: Derived from SimplePeerMessage. (msg): New variable. (create): New function. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/RequestMessage.cc (create): New function. (receivedAction): Added the handling of fast extension. Deleted torrentMan->addUploadLength, torrentMan->addDeltaUploadLength. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/InterestedMessage.h: Derived from SimplePeerMessage. (msg): New variable. (sendPredicate): New function. (onSendComplete): New function. (create): New function. (getMessage): New function. (getMessageLength): New function. * src/InterestedMessage.cc (create): New function. (send): Removed. (sendPieceData): New function. (getMessage): New function. (getMessageLength): New function. (onSendComplete): New function. * src/NotInterestedMessage.h: Derived from SimplePeerMessage. (msg): New variable. (sendPieceData): New function. (onSendComplete): New function. (create): New function. (send): Removed. (getMessage): New function. (getMessageLength): New function. * src/NotInterestedMessage.cc (create): New function. (send): Removed. (sendPredicate): New function. (getMessage): New function. (getMessageLength): New function. (onSendComplete): New function. * src/AllowedFastMessage.h: New class. * src/AllowedFastMessage.cc: New class. * src/RejectMessage.h: New class. * src/RejectMessage.cc: New class. * src/SuggestPieceMessage.h: New class. * src/SuggestPieceMessage.cc: New class. * src/HaveAllMessage.h: New class. * src/HaveAllMessage.cc: New class. * src/HaveNoneMessage.h: New class. * src/HaveNoneMessage.cc: New class. * src/HandshakeMessage.h: Derived from SimplePeerMessage. (msg): New variable. (reserved): New variable. (create): New function. (getId): New function. (receivedAction): New function. (getMessage): New function. (getMessageLength): New function. (isFastExtensionSupported): New function. * src/HandshakeMessage.cc (HandshakeMessage): Moved here from HandshakeMessage.h. (create): New function. (getMessage): New function. (getMessageLength): New function. (toString): Added the output of reserved field. (check): Added const qualifier. (isFastExtensionSupported): New function. * src/PeerMessageUtil.h (createChokeMessage): Removed. (createUnchokeMessage): Removed. (createInterestedMessage): Removed. (createNotInterestedMessage): Removed. (createHaveMessage): Removed. (createBitfieldMessage): Removed. (createRequestMessage): Removed. (createCancelMessage): Removed. (createPieceMessage): Removed. (createPortMessage): Removed. (createChokeMessage): Removed. (createUnchokeMessage): Removed. (createInterestedMessage): Removed. (createNotInterestedMessage): Removed. (createHaveMessage): Removed. (createBitfieldMessage): Removed. (createRequestMessage): Removed. (createCancelMessage): Removed. (createPieceMessage): Removed. (createKeepAliveMessage): Removed. (createHandshakeMessage): Removed. (setIntParam): New function. (createPeerMessageString): New function. * src/PeerMessageUtil.cc (createChokeMessage): Removed. (createUnchokeMessage): Removed. (createInterestedMessage): Removed. (createNotInterestedMessage): Removed. (createHaveMessage): Removed. (createBitfieldMessage): Removed. (createRequestMessage): Removed. (createCancelMessage): Removed. (createPieceMessage): Removed. (createPortMessage): Removed. (createRequestMessage): Removed. (createCancelMessage): Removed. (createPieceMessage): Removed. (createHaveMessage): Removed. (createChokeMessage): Removed. (createUnchokeMessage): Removed. (createInterestedMessage): Removed. (createNotInterestedMessage): Removed. (createBitfieldMessage): Removed. (createKeepAliveMessage): Removed. (createHandshakeMessage): Removed. (setIntParam): New function. (createPeerMessageString): New function. * src/PeerConnection.h (peer): Removed. (torrentMan): Removed. (createNLengthMessage): Removed. (setIntParam): Removed. (writeOutgoingMessageLog): Removed all overloaded functions. (PeerConnection): Deleted peer and torrentMan from its arguments. (sendMessage): New function. (sendHandshake): Removed. (sendKeepAlive): Removed. (sendChoke): Removed. (sendUnchoke): Removed. (sendInterested): Removed. (sendNotInterested): Removed. (sendHave): Removed. (sendBitfield): Removed. (sendRequest): Removed. (sendPiece): Removed. (sendPieceHeader): Removed. (sendPieceData): Removed. (sendCancel): Removed. (getPeer): Removed. * src/PeerConnection.cc (PeerConnection): Deleted peer and torrentMan from its arguments. (sendHandshake): Removed. (sendKeepAlive): Removed. (createNLengthMessage): Removed. (setIntParam): Removed. (writeOutgoingMessageLog): Removed all overloaded functions. (sendChoke): Removed. (sendUnchoke): Removed. (sendInterested): Removed. (sendNotInterested): Removed. (sendHave): Removed. (sendBitfield): Removed. (sendRequest): Removed. (sendPiece): Removed. (sendPieceHeader): Removed. (sendPieceData): Removed. (sendMessage): New function. (sendCancel): Removed. * src/PeerInteractionCommand.cc (PeerInteractionCommand): Call setUploadLimit. (executeInternal): Call setUploadLimit. Added the handling of "inProgress" state of handshake message. Call sendBitfield() or sendAllowdFast() instead of deprecated sendNow(). (keepAlive): Call addMessage and sendMessage instead of deprecated sendNow(). (beforeSocketCheck): Call addMessage instead of deprecated trySendNow() * src/TorrentMan.h (PEER_ID_LENGTH): New definition. (hasAllPieces): New function. * src/TorrentMan.cc (getMissingPiece): Added the handling of fast extension. (cancelPiece): Call updatePiece(). (hasAllPieces): New function. * src/PeerInteraction.h (fastSet): New variable. (getNewPieceAndSendInterest): Changed the return type to void. (send): Renamed as sendMessages. (deleteAllRequestSlot): Removed. (deleteRequestMessageInQueue): Renamed as rejectPieceMessageInQueue. (cancelAllRequest): Removed all overloaded functions. (deleteAllRequestSlot): Removed. (deletePieceMessageInQueue): Renamed as rejectAllPieceMessageInQueue. (rejectPieceMessageInQueue): New function. (rejectAllPieceMessageInQueue): New function. (onChoked): New function. (isSendingMessageInProgress): New function. (getCorrespondingRequestSlot): Changed its arguments. (isInFastSet): New function. (addFastSetIndex): New function. (addRequests): New function. (sendNow): Removed. (trySendNow): Removed. (sendBitfield): New function. (sendAllowdFast): New function. (createHaveAllMessage): New function. (createHaveNoneMessage): New function. (createRejectMessage): New function. (createAllowedFastMessage): New function. * src/PeerInteraction.cc (send): Renamed as sendMessages. (sendMessages): New function. (MsgPushBack): New class. (isSendingMessageInProgress): New function. (deletePieceMessageInQueue): Renamed as rejectAllPieceMessageInQueue. (rejectAllPieceMessageInQueue): New function. Added the handling of fast extension. (deleteRequestMessageInQueue): Renamed as rejectPieceMessageInQueue. (rejectPieceMessageInQueue): New function. Added the handling of fast extension. (deleteRequestSlot): Replaced for loop with std::find. (onChoked): New function. (deleteAllRequestSlot): Removed. (abortPiece): Rewirtten. (deleteTimeoutRequestSlot): Updated log messages. (getCorrespondingRequestSlot): Changed its arguments. (cancelAllRequest): Removed all overloaded functions. (receiveHandshake): Added the check to see whether an incoming peer supports fast extension. (createHandshakeMessage): Use HandshakeMessage::create instead of PeerMessageUtil. (createPeerMessage): Use create() of each message class instead of PeerMessageUtil. HaveAllMessage, HaveNoneMessage, RejectMessage, SuggestPieceMessage, AllowedFastMessage were added. (getNewPieceAndSendInterest): Changed its return value type to void. Added the handling of fast extension. (addRequests): New function. (sendNow): Removed. (sendHandshake): Rewritten. (trySendNow): Removed. (sendBitfield): New function. (sendAllowdFast): New function. (isInFastSet): New function. (addFastSetIndex): New function. (createRequestMessage): Use RequestMessage::create instead of PeerMessageUtil. (createCancelMessage): Use CancelMessage::create instead of PeerMessageUtil. (createPieceMessage): Use PieceMessage::create instead of PeerMessageUtil. (createHaveMessage): Use HaveMessage::create instead of PeerMessageUtil. (createChokeMessage): Use ChokeMessage::create instead of PeerMessageUtil. (createUnchokeMessage): Use UnchokeMessage::create instead of PeerMessageUtil. (createInterestedMessage): Use InterestedMessage::create instead of PeerMessageUtil. (createNotInterestedMessage): Use NotInterestedMessage::create instead of PeerMessageUtil. (createBitfieldMessage): Use BitfieldMessage::create instead of PeerMessageUtil. (createKeepAliveMessage): Use KeepAliveMessage::create instead of PeerMessageUtil. (createHaveAllMessage): New function. (createHaveNoneMessage): New function. (createRejectMessage): New function. (createAllowedFastMessage: New function. * src/Util.h (sha1Sum): New function. (computeFastSet): New function. * src/Util.cc (sha1Sum): New function. (computeFastSet): New function. * src/Peer.h (fastExtensionEnabled): New variable. (fastSet): New variable. (setAllBitfield): New function. (setFastExtensionEnabled): New function. (isFastExtensionEnabled): New function. (addFastSetIndex): New function. (getFastSet): New function. (isInFastSet): New function. (countFastSet): New function. * src/Peer.cc (isInFastSet): New function. (addFastSetIndex): New function. (setAllBitfield): New function. * src/AbstractCommand.cc (execute): Changed the procedure of checking sockets. * src/PeerAbstractCommand.cc (PeerAbstractCommand): Added the initialization for uploadLimitCheck and uploadLimit. (execute): Changed the procedure of checking sockets. The upload speed checking were added. (setUploadLimit): New function. (setUploadLimitCheck): New function. * src/PeerAbstractCommand.h (setUploadLimit): New function. (setUploadLimitCheck): New function. (uploadLimit): New variable. (uploadLimitCheck): New variable. To contact a tracker regularly: * src/TrackerWatcherCommand.h (interval): New variable. (checkPoint): New variable. (TrackerWatcherCommand): Added interval argument. * src/TrackerWatcherCommand.cc (TrackerWatcherCommand): Initialized checkPoint. (execute): Now a tracker is contacted in every specified period. If peer list is not needed, send request with numwant=0. * src/TrackerUpdateCommand.cc (execute): Updated log messages. * src/DownloadEngine.cc (~DownloadEngine): Removed two asserts. (waitData): Uncommented wfds. May be a bug fix.
2006-05-18 17:08:29 +00:00
std::string randomAlpha(size_t length,
const SharedHandle<Randomizer>& randomizer);
2007-08-08 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> MessageDigestHelper is introduced in order to simplify the use of message digest. Removed repeated code. The message digest algorithm is now specified by string, like "sha1", "md5". * src/messageDigest.{h, cc} * src/MessageDigestHelper.{h, cc}: New class. * src/DefaultPieceStorage.cc * src/DefaultBtContext.{h, cc} (computeFastSet): New function. (setInfoHash): Added for unit testing. (setNumPieces): Added for unit testing. * src/DefaultBtInteractive.cc * src/BtPieceMessage.cc * src/Peer.cc * src/Checksum.h * src/message.h * src/IteratableChecksumValidator.h * src/ChunkChecksumValidator.{h, cc}: Use IteratableChecksumValidator inside it. * src/SegmentMan.{h, cc} (checkIntegrity): Removed. * src/IteratableChunkChecksumValidator.{h, cc} * src/Util.h (sha1Sum): Removed. (simpleMessageDigest): Removed. (fileChecksum): Removed. (computeFastSet): Removed. * src/ShaVisitor.cc * src/ChunkChecksum.h * src/DownloadCommand.cc Removed messageDigest virtual functions. * src/MultiDiskAdaptor.{h, cc} * src/DiskAdaptor.h * src/ByteArrayDiskWriter.h * src/DiskWriter.h * src/DiskAdaptorWriter.h * src/AbstractSingleDiskAdaptor.{h, cc} * src/AbstractDiskWriter.{h, cc} Fixed comilation error when message digest is disabled. * src/MetalinkEntry.{h, cc} * src/MetalinkRequestInfo.cc Removed srandom and random. * src/SimpleRandomizer.h Added size() virtual function to DiskAdaptor * src/MultiDiskAdaptor.h Fixed the bug that causes that files are not opened correctly in multi-file torrent. * src/TorrentRequestInfo.cc * src/MultiDiskAdaptor.cc Added SHA256 support * src/messageDigest.cc * src/Xml2MetalinkProcessor.cc Show supported message digest algorithms * src/main.cc Updated contact info. * src/main.cc
2007-08-08 14:40:11 +00:00
std::string toUpper(const std::string& src);
2006-07-03 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To add Metalink support(http/ftp only): * src/AbstractCommand.h (tryReserved): New function. * src/AbstractCommand.cc (execute): Call tryReserved(). (tryReserved): New function. * src/Request.h (Requests): New type definition. * src/SegmentMan.h (reserved): New variable. * src/Util.h (fileChecksum): New function. (toUpper): New function. (toLower): New function. * src/Util.cc (messageDigest.h): Included. (trim): Trim \r\n\t. (fileChecksum): New function. (toUpper): New function. (toLower): New function. * src/main.cc (normalDownload): New function. (main): Added 2 command-line options: metalink-file, metalink-connection. Their usage has not been written yet. * src/MetalinkProcessor.h: New class. * src/Xml2MetalinkProcessor.h: New class. * src/Xml2MetalinkProcessor.cc: New class. * src/MetalinkEntry.h: New class. * src/MetalinkEntry.cc: New class. * src/MetalinkResource.h: New class. * src/MetalinkResource.cc: New class. To add md5 message digest checking: * src/messageDigest.h: Rewritten. * src/MultiDiskWriter.cc: Updated according to the changes in messageDigest.h. * src/ShaVisitor.cc: Updated according to the changes in messageDigest.h. * src/Util.cc: Updated according to the changes in messageDigest.h. * src/AbstractDiskWriter.cc: Updated according to the changes in messageDigest.h. To fix a bug that causes segfault when the payload length in peer message is less than 0: * src/PeerConnection.cc: (receiveMessage): Fixed the bug. * src/PeerMessageUtil.cc (checkLength): Throw an exception if length is less than or equals to 0. To add new interfaces to Base64 encoding/decoding: * src/Base64.h (part_encode): Changed the method signature. (encode): New function(overload). (decode): New function(overload). * src/Base64.cc (part_encode): Rewritten. (encode): Rewritten. (encode): New function(overload). To prevent a peer to download same piece if there is an error in checksum: * src/PieceMessage.cc (receivedAction): Call peerInteraction->abortPiece().
2006-07-03 14:19:23 +00:00
std::string toLower(const std::string& src);
2006-08-11 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To add asynchronous DNS support(libares): * src/AbstractCommand.h (setNameResolverCheck): New function. (disableNameResolverCheck): New function (resolveHostname): New function. * src/AbstractCommand.cc (setNameResolverCheck): New function. (disableNameResolverCheck): New function (resolveHostname): New function. * src/FtpInitiateConnectionCommand.h (nameResolver): New function. * src/FtpInitiateConnectionCommand.cc (Util.h): Included. (FtpInitiateConnectionCommand): Call disableReadCheckSocket, disableWriteCheckSocket. (~FtpInitiateConnectionCommand): Call disableNameResolverCheck. (executeInternal): Added async DNS support. * src/HttpInitiateConnectionCommand.h (nameResolver): New function. * src/HttpInitiateConnectionCommand.cc (DlRetryEx.h): Included. (HttpInitiateConnectionCommand): Call disableReadCheckSocket, disableWriteCheckSocket. (~HttpInitiateConnectionCommand): Call disableNameResolverCheck. (executeInternal): Added async DNS support. * src/NameResolver.h: New class. Note: #include <ares.h> is surrounded by extern "C" declaration. * src/NameResolver.cc: New class. * src/Util.h: (isNumberAndDotsNotation): New function * src/Util.cc (isNumberAndDotsNotation): New function. * src/DownloadEngine.h (NameResolver.h): Included. (NameResolverEntry): New class. (NameResolverEntries): New type definition. (addNameResolverCheck): New function. (deleteNameResolverCheck): New function. * src/DownloadEngine.cc (run): Initialize cp with 0. (SetDescriptor::operator()): Added for NameResolverEntry. (AccumulateActiveUuid::operator()): Added for NameResolverEntry. (waitData): Check nameResolver entries. (updateFdSet): Update fds in nameResolver entries. (addNameResolverCheck): New function. (deleteNameResolverCheck): new function. * src/PeerInteractionCommand.cc (executeInternal): Fixed wrong socket handling. * src/main.cc (main): Fixed the initial value of PREF_LOWEST_SPEED_LIMIT option to 0. * src/Util.cc (fileChecksum): Removed the call to ctx.digestReset().
2006-08-11 12:29:55 +00:00
void uppercase(std::string& s);
void lowercase(std::string& s);
bool isNumericHost(const std::string& name);
void setGlobalSignalHandler(int signal, void (*handler)(int), int flags);
2007-01-23 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To add chunk checksum validation: * src/MetalinkEntry.h (MetalinkChunkChecksum.h): New include. (chunkChecksum): New variable. * src/Request.h (method): New variable. (setMethod): New function. (getMethod): New function. (METHOD_GET): New static constant. (METHOD_HEAD): New static constant. * src/Xml2MetalinkProcessor.h (getPieceHash): New function. * src/PieceStorage.h (markAllPiecesDone): New function. (checkIntegrity): New function. * src/FileAllocator.h (NullFileAllocationMonitor.h): New include. (FileAllocator): Initialize fileAllocationMonitor with new NullFileAllocationMonitor(). * src/MultiDiskAdaptor.h (messageDigest.h): Remove include. (ctx): Removed. (hashUpdate): Added ctx. (MultiDiskAdaptor): Removed ctx. (sha1Sum): Renamed as messageDigest. (messageDigest): New function. * src/UrlRequestInfo.h (HeadResult): New class. (digestAlgo): New variable. (chunkChecksumLength): New variable. (chunkChecksums): New variable. (getHeadResult): New function. (UrlRequestInfo): Added digestAlgo, chunkChecksumLength. (setDigestAlgo): New function. (setChunkChecksumLength): New function. (setChunkChecksums): New function. * src/DefaultPieceStorage.cc (DiskAdaptorWriter.h): New include. (ChunkChecksumValidator.h): New include. (markAllPiecesDone): New function. (checkIntegrity): New function. * src/DefaultBtContext.h (getPieceHashes): New function. * src/TorrentRequestInfo.cc (execute): Try to validate chunk checksum if file already exists and .aria2 file doesn't there and user allows aria2 to overwrite it. * src/messageDigest.h (~MessageDigestContext): Added digestFree(). * src/MetalinkRequestInfo.cc (execute): Set digestAlgo, chunkChecksum, chunkChecksums to reqInfo. * src/DiskAdaptor.h (messageDigest.h): New include. (sha1Sum): Renamed as messageDigest. (messageDigest): New function. * src/DownloadCommand.h (PeerStat.h): New include. (maxDownloadSpeedLimit): New variable. (startupIdleTime): New variable. (lowestDownloadSpeedLimit): New variable. (peerStat): New variable. (setMaxDownloadSpeedLimit): New function. (setStartupIdleTime): New function. (setLowestDownloadSPeedLimit): New function. * src/BtContext.h (getPieceHashes): New function. * src/main.cc (main): Set PREF_REALTIME_CHUNK_CHECKSUM and PREF_CHECK_INTEGRITY option to true for testing purpose. * src/BtPieceMessage.cc (checkPieceHash): Use messageDigest * src/DownloadEngine.cc (SetDescriptor): Removed. (AccumulateActiveCommand): Removed. (waitData): Rewritten. (updateFdSet): Rewritten. * src/MultiDiskAdaptor.cc (hashUpdate): Added ctx. (sha1Sum): Renamed as messageDigest. (messageDigest): New function. * src/BitfieldMan.h (isBitRangeSet): New function. (unsetBitRange): New function. * src/ByteArrayDiskWriter.h (sha1Sum): Renamed as messageDigest. (messageDigest): New function. * src/ConsoleDownloadEngine.cc (calculateStatistics): If nspeed < 0 then set nspeed to 0. * src/DiskWriter.h (messageDigest.h): New include. (sha1Sum): Renamed as messageDigest. (messageDigest): New function. * src/ChunkChecksumValidator.h: New class. * src/DiskAdaptorWriter.h: New class. * src/prefs.h (PREF_REALTIME_CHUNK_CHECKSUM): New definition. (PREF_CHECK_INTEGRITY): New definition. * src/HttpResponseCommand.cc (handleDefaultEncoding): Added method "HEAD" handling. Removed the call to e->segmentMan->shouldCancelDownloadForSafety(). (handleOtherEncoding): Added the call to e->segmentMan->shouldCancelDownloadForSafety(). (createHttpDownloadCommand): Set maxDownloadSpeedLimit, startupIdleTime, lowestDownloadSpeedLimit to command. * src/SegmentMan.h (getSegmentEntryByIndex): New function. (getSegmentEntryByCuid): New function. (getSegmentEntryIteratorByCuid): New function. (diskWriter): DiskWriter -> DiskWriterHandle (pieceHashes): New variable. (chunkHashLength): New variable. (digestAlgo): New variable. (FindPeerStat): Removed. (getPeerStat): Rewritten. (markAllPiecesDone): New function. (checkIntegrity): New function. (tryChunkChecksumValidation): New function. (isChunkChecksumValidationReady): New function. * src/BitfieldMan.cc (BitfieldMan): Initialized bitfieldLength, blocks to 0. (BitfieldMan): Initialized blockLength, totalLength, bitfieldLength, blocks to 0. (isBitRangeSet): New function. (unsetBitRange): New function. * src/FtpNegotiateCommand.cc (executeInternal): Set maxDownloadSpeedLimit, startupIdleTime, lowestDownloadSpeedLimit to command. (recvSize): Added method "HEAD" handling. Removed the call to e->segmentMan->shouldCancelDownloadForSafety(). * src/AbstractSingleDiskAdaptor.cc (sha1Sum): Renamed as messageDigest. (messageDigest): New function. * src/AbstractSingleDiskAdaptor.h (sha1Sum): Renamed as messageDigest. (messageDigest): New function. * src/Util.h (indexRange): New function. * src/MetalinkEntry.cc (MetalinkEntry): Initialized chunkChecksum to 0. * src/ShaVisitor.cc (~ShaVisitor): Removed the call to ctx.digestFree(). * src/SegmentMan.cc (ChunkChecksumValidator.h): New include. (SegmentMan): Initialized chunkHashLength to 0. Initialized digestAlgo to DIGEST_ALGO_SHA1. (~SegmentMan): Removed diskWriter. (FindSegmentEntryByIndex): Removed. (FindSegmentEntryByCuid): Removed. (checkoutSegment): Rewritten. (findSlowerSegmentEntry): Rewritten. (getSegment): Rewritten. (updateSegment): Rewritten. (completeSegment): Rewritten. (markAllPiecesDone): New function. (checkIntegrity): New function. (isChunkChecksumValidationReady): New function. (tryChunkChecksumValidation): New function. * src/Xml2MetalinkProcessor.cc (getEntry): Get size and set it to entry. Get chunk checksum and set it to entry. (getPieceHash): New function. * src/Util.cc (sha1Sum): Removed ctx.digestFree() (fileChecksum): Removed ctx.digestFree() (indexRange): New function. * src/Request.cc (METHOD_GET): New variable. (METHOD_HEAD): New variable. (Request): Added method. * src/UrlRequestInfo.cc (FatalException.h): New include. (message.h): New include. (operator<<): Added operator<< for class HeadResult. (getHeadResult): New function. (execute): Get filename and size in separate download engine. * src/ChunkChecksumValidator.cc: New class. * src/DownloadCommand.cc: (DownloadCommand): Added peerStat. (executeInternal): Use maxDownloadSpeedLimit member instead of getting the value from Option. The buffer size is now 16KB. Use peerStat member instead of getting it from SegmentMan. Use startupIdleTime member instead of gettingit from Option. Added chunk checksum validation. * src/AbstractDiskWriter.cc (AbstractDiskWriter): Removed ctx. (~AbstractDiskWriter): Removed ctx.digestFree() (writeDataInternal): Returns the return value of write. (readDataInternal): Returns the return value of read. (sha1Sum): Renamed as messageDigest (messageDigest): New function. * src/AbstractDiwkWriter.h (messageDigest.h): Removed include. (ctx): Removed. (sha1Sum): Renamed as messageDigest (messageDigest): New function. * src/DefaultPieceStorage.h (markAllPiecesDone): New function. (checkIntegrity): New function. * src/NullFileAllocationMonitor.h: New class.
2007-01-24 15:55:34 +00:00
std::string getHomeDir();
int64_t getRealSize(const std::string& sizeWithUnit);
std::string abbrevSize(int64_t size);
2007-06-10 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> * src/AbstractCommand.cc (execute): Changed log level of MSG_RESTARTING_DOWNLOAD and MSG_MAX_TRY from error to info. Added MSG_DOWNLOAD_ABORTED after MSG_MAX_TRY. * src/message.h (MSG_TORRENT_DOWNLOAD_ABORTED): New definition. (MSG_DOWNLOAD_ABORTED): Added %s. (MSG_RESTARTING_DOWNLOAD): Added %s. (MSG_DOWNLOAD_ALREADY_COMPLETED): Updated. * src/PeerAbstractCommand.cc (execute): MSG_DOWNLOAD_ABORTED -> MSG_TORRENT_DOWNLOAD_ABORTED * src/Request.h (cookieBox): Made ShardHandle. * src/RequestGroup.h, src/RequestGroup.cc (createNextCommandWithAdj): New function. * src/FileAllocationCommand.cc (executeInternal): Use createNextCommandWithAdj(). * src/CheckIntegrityCommand.cc (executeInternal): Use createNextCommandWithAdj(). Added --load-cookies command-option. * src/OptionHandlerFactory.cc (createOptionHandlers): Added PREF_LOAD_COOKIES. * src/CookieBox.h, src/CookieBox.cc: Rwritten using CookieParser. Now aria2 can handle cookie's expiration date. * src/Cookie.h (expires): Changed its type to time_t. * src/main.cc: Added --load-cookies command-line option. * src/prefs.h (PREF_LOAD_COOKIES): New definition. * src/Util.h, src/Util.cc (httpGMT): New function. * src/Request.cc (Request): Initialize cookieBox using CookieBoxFactory. * src/CookieBoxFactory.h, src/CookieBoxFactory.cc: New class. * src/CookieParser.h, src/CookieParser.cc: New class. * src/main.cc: Chagned the default value of --metalink-servers to 5. * src/HttpResponseCommand.cc (handleOtherEncoding): Call RequestGroup::shouldCancelDownloadForSafety
2007-06-10 07:55:43 +00:00
template<typename InputIterator, typename Output>
void toStream
(InputIterator first, InputIterator last, Output& os)
{
os.printf("%s\n"
"idx|path/length\n"
"===+===========================================================================\n", _("Files:"));
int32_t count = 1;
for(; first != last; ++first, ++count) {
os.printf("%3d|%s\n"
" |%sB (%s)\n"
"---+---------------------------------------------------------------------------\n",
count,
(*first)->getPath().c_str(),
util::abbrevSize((*first)->getLength()).c_str(),
util::uitos((*first)->getLength(), true).c_str());
2009-06-28 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net> Rewritten DownloadContext and removed SingleFileDownloadContext and BtContext and its derived classes. BitTorrent specific attributes are now set by DownloadContext::setAttribute() with key bittorrent::BITTORRENT. * src/AbstractBtMessage.cc * src/AbstractBtMessage.h * src/AbstractCommand.cc * src/AbstractCommand.h * src/AbstractProxyRequestCommand.cc * src/AbstractProxyResponseCommand.cc * src/ActivePeerConnectionCommand.cc * src/ActivePeerConnectionCommand.h * src/AnnounceList.cc * src/BtCheckIntegrityEntry.cc * src/BtConstants.h * src/BtContext.h: Removed * src/BtDependency.cc * src/BtExtendedMessage.cc * src/BtPieceMessage.cc * src/BtPieceMessage.h * src/BtPostDownloadHandler.cc * src/BtRegistry.cc * src/BtRegistry.h * src/BtSetup.cc * src/CheckIntegrityCommand.cc * src/CheckIntegrityEntry.cc * src/ChecksumCheckIntegrityEntry.cc * src/ConsoleStatCalc.cc * src/ContentTypeRequestGroupCriteria.cc * src/DHTGetPeersCommand.cc * src/DHTGetPeersCommand.h * src/DHTPeerLookupTask.cc * src/DHTPeerLookupTask.h * src/DHTTaskFactory.h * src/DHTTaskFactoryImpl.cc * src/DHTTaskFactoryImpl.h * src/DefaultBtAnnounce.cc * src/DefaultBtAnnounce.h * src/DefaultBtContext.cc: Removed * src/DefaultBtContext.h: Removed * src/DefaultBtInteractive.cc * src/DefaultBtInteractive.h * src/DefaultBtMessageDispatcher.cc * src/DefaultBtMessageDispatcher.h * src/DefaultBtMessageFactory.cc * src/DefaultBtMessageFactory.h * src/DefaultBtMessageReceiver.cc * src/DefaultBtMessageReceiver.h * src/DefaultBtProgressInfoFile.cc * src/DefaultBtRequestFactory.cc * src/DefaultBtRequestFactory.h * src/DefaultExtensionMessageFactory.cc * src/DefaultExtensionMessageFactory.h * src/DefaultPeerStorage.cc * src/DefaultPeerStorage.h * src/DefaultPieceStorage.cc * src/DefaultSegmentManFactory.cc * src/DiskAdaptor.cc * src/DiskAdaptor.h * src/DownloadContext.cc * src/DownloadContext.h * src/DownloadEngine.cc * src/DownloadEngineFactory.cc * src/DownloadHandler.cc * src/DownloadResult.h * src/FileAllocationCommand.cc * src/FileAllocationDispatcherCommand.cc * src/FileAllocationEntry.cc * src/FileEntry.h * src/FillRequestGroupCommand.cc * src/FtpDownloadCommand.cc * src/FtpFinishDownloadCommand.cc * src/FtpInitiateConnectionCommand.cc * src/FtpNegotiationCommand.cc * src/FtpTunnelRequestCommand.cc * src/FtpTunnelResponseCommand.cc * src/HandshakeExtensionMessage.cc * src/HandshakeExtensionMessage.h * src/HaveEraseCommand.cc * src/HttpDownloadCommand.cc * src/HttpInitiateConnectionCommand.cc * src/HttpProxyRequestCommand.cc * src/HttpProxyResponseCommand.cc * src/HttpRequest.cc * src/HttpRequest.h * src/HttpRequestCommand.cc * src/HttpResponseCommand.cc * src/HttpServerBodyCommand.cc * src/HttpServerCommand.cc * src/HttpSkipResponseCommand.cc * src/InitiateConnectionCommandFactory.cc * src/InitiatorMSEHandshakeCommand.cc * src/InitiatorMSEHandshakeCommand.h * src/IteratableChecksumValidator.cc * src/IteratableChecksumValidator.h * src/IteratableChunkChecksumValidator.cc * src/MSEHandshake.cc * src/MSEHandshake.h * src/Makefile.am * src/Makefile.in * src/Metalink2RequestGroup.cc * src/MetalinkPostDownloadHandler.cc * src/MultiDiskAdaptor.cc * src/MultiDiskAdaptor.h * src/MultiFileAllocationIterator.cc * src/MultiUrlRequestInfo.cc * src/PeerChokeCommand.cc * src/PeerChokeCommand.h * src/PeerInitiateConnectionCommand.cc * src/PeerInitiateConnectionCommand.h * src/PeerInteractionCommand.cc * src/PeerInteractionCommand.h * src/PeerReceiveHandshakeCommand.cc * src/PieceHashCheckIntegrityEntry.cc * src/RealtimeCommand.cc * src/ReceiverMSEHandshakeCommand.cc * src/RequestGroup.cc * src/RequestGroup.h * src/RequestGroupEntry.cc * src/RequestGroupMan.cc * src/SeedCheckCommand.cc * src/SeedCheckCommand.h * src/SegmentMan.cc * src/ShareRatioSeedCriteria.h * src/SingleFileDownloadContext.cc: Removed * src/SingleFileDownloadContext.h: Removed * src/SleepCommand.cc * src/StreamCheckIntegrityEntry.cc * src/TrackerWatcherCommand.cc * src/TrackerWatcherCommand.h * src/UnknownLengthPieceStorage.cc * src/Util.cc * src/Util.h * src/XmlRpcMethodImpl.cc * src/bittorrent_helper.cc * src/bittorrent_helper.h * src/download_helper.cc * src/main.cc * src/option_processing.cc * test/BitfieldManTest.cc * test/BittorrentHelperTest.cc * test/BtCancelMessageTest.cc * test/BtChokeMessageTest.cc * test/BtDependencyTest.cc * test/BtPieceMessageTest.cc * test/BtPostDownloadHandlerTest.cc * test/BtRegistryTest.cc * test/BtRejectMessageTest.cc * test/BtRequestMessageTest.cc * test/DHTPeerAnnounceStorageTest.cc * test/DefaultBtAnnounceTest.cc * test/DefaultBtContextTest.cc: Removed * test/DefaultBtMessageDispatcherTest.cc * test/DefaultBtMessageFactoryTest.cc * test/DefaultBtProgressInfoFileTest.cc * test/DefaultBtRequestFactoryTest.cc * test/DefaultExtensionMessageFactoryTest.cc * test/DefaultPeerStorageTest.cc * test/DefaultPieceStorageTest.cc * test/DirectDiskAdaptorTest.cc * test/DownloadContextTest.cc * test/DownloadHandlerFactoryTest.cc * test/DownloadHelperTest.cc * test/HandshakeExtensionMessageTest.cc * test/HttpRequestTest.cc * test/HttpResponseTest.cc * test/IteratableChecksumValidatorTest.cc * test/IteratableChunkChecksumValidatorTest.cc * test/MSEHandshakeTest.cc * test/Makefile.am * test/Makefile.in * test/Metalink2RequestGroupTest.cc * test/MetalinkPostDownloadHandlerTest.cc * test/MockBtContext.h: Removed * test/MockDHTTaskFactory.h * test/MockDownloadContext.h: Removed * test/MockPieceStorage.h * test/MultiDiskAdaptorTest.cc * test/MultiFileAllocationIteratorTest.cc * test/RequestGroupManTest.cc * test/RequestGroupTest.cc * test/SegmentManTest.cc * test/ShareRatioSeedCriteriaTest.cc * test/SingleFileDownloadContextTest.cc: Removed * test/UtilTest.cc * test/XmlRpcMethodTest.cc
2009-06-28 10:37:15 +00:00
}
}
void sleep(long seconds);
void usleep(long microseconds);
template<typename InputIterator>
bool isNumber(InputIterator first, InputIterator last)
{
if(first == last) {
return false;
}
for(; first != last; ++first) {
if('0' > *first || *first > '9') {
return false;
}
}
return true;
}
bool isDigit(const char c);
bool isHexDigit(const char c);
bool isHexDigit(const std::string& s);
template<typename InputIterator>
bool isLowercase(InputIterator first, InputIterator last)
{
if(first == last) {
return false;
}
for(; first != last; ++first) {
if('a' > *first || *first > 'z') {
return false;
}
}
return true;
}
template<typename InputIterator>
bool isUppercase(InputIterator first, InputIterator last)
{
if(first == last) {
return false;
}
for(; first != last; ++first) {
if('A' > *first || *first > 'Z') {
return false;
}
}
return true;
}
/**
* Converts alphabets to unsigned int, assuming alphabets as a base 26
* integer and 'a' or 'A' is 0.
* This function assumes alphabets includes only a-z.
* Upper case are allowed but all letters must be upper case.
* If overflow occurs, returns 0.
*/
unsigned int alphaToNum(const std::string& alphabets);
void mkdirs(const std::string& dirpath);
void convertBitfield(BitfieldMan* dest, const BitfieldMan* src);
2007-11-27 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> Rewritten to add content-type support. * src/DownloadHandler.{h, cc} * src/BtPostDownloadHandler.{h, cc} * test/BtPostDownloadHandlerTest.cc * src/MetalinkPostDownloadHandler.{h, cc} * test/MetalinkPostDownloadHandlerTest.cc * src/PostDownloadHandler.{h, cc} * src/DownloadHandlerConstants.{h, cc} * src/RequestGroup.cc * src/HttpResponseCommand.cc * src/FtpNegotiationCommand.cc * src/SingleFileDownloadContext.{h, cc} * src/RequestGroup.h * src/RequestGroupCriteria.h * src/ContentTypeRequestGroupCriteria.h Added 'mem' option value for --follow-metalink, --follow-torrent. If it is give, metalink/torrent file is not written to the disk, but just is kept in memory. Parsing is occurred on memory. * src/MetalinkHelper.{h, cc} * src/MetalinkProcessor.h * src/Xml2MetalinkProcessor.{h, cc} * test/Xml2MetalinkProcessorTest.cc * src/DownloadHandlerFactory.{h, cc} * test/DownloadHandlerFactoryTest.cc * src/PreDownloadHandler.{h, cc} * src/OptionHandlerFactory.cc * src/DefaultBtContext.{h, cc} * test/DefaultBtContextTest.cc * src/version_usage.cc * src/Metalink2RequestGroup.{h, cc} * src/RequestGroup.{h, cc} * src/a2functional.h * test/a2functionalTest.cc * src/MemoryBufferPreDownloadHandler.{h, cc} * src/OptionHandlerImpl.h * src/prefs.h * src/Util.{h, cc} * test/UtilTest.cc Keep DownloadResult rather than RequestGroup after downloads to reduce memory usage. * src/RequestGroupMan.{h, cc} * src/DownloadEngine.cc * src/BtDependency.{h, cc}: Changed the type of dependee from WeakHandle to SharedHandle because WeakHandle could be null. * src/RequestGroup.{h, cc} * src/DownloadEngineFactory.cc * src/DownloadResult.h Set totalLength after download finished * src/UnknownLengthPieceStorage.{h, cc} Keep torrent file specified in metalink in memory. * src/Metalink2RequestGroup.cc * src/BtDependency.cc * src/TrueRequestGroupCriteria.h Fixed the bug: seekg is used where seekp should be used. * src/ByteArrayDiskWriter.cc * test/ByteArraydiskWriterTest.cc
2007-11-27 12:27:10 +00:00
// binaryStream has to be opened before calling this function.
std::string toString(const SharedHandle<BinaryStream>& binaryStream);
#ifdef HAVE_POSIX_MEMALIGN
void* allocateAlignedMemory(size_t alignment, size_t size);
#endif // HAVE_POSIX_MEMALIGN
std::pair<std::string, uint16_t>
getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len);
std::string htmlEscape(const std::string& src);
// Joins path element specified in [first, last). If ".." is found,
// it eats the previous element if it exists. If "." is found, it
// is just ignored and it is not appeared in the result.
template<typename InputIterator>
std::string joinPath(InputIterator first, InputIterator last)
{
std::vector<std::string> elements;
for(;first != last; ++first) {
if(*first == "..") {
if(!elements.empty()) {
elements.pop_back();
}
} else if(*first == ".") {
// do nothing
} else {
elements.push_back(*first);
}
}
return strjoin(elements.begin(), elements.end(), "/");
}
// Parses INDEX=PATH format string. INDEX must be an unsigned
// integer.
std::pair<size_t, std::string>
parseIndexPath(const std::string& line);
std::vector<std::pair<size_t, std::string> > createIndexPaths(std::istream& i);
2006-02-17 13:35:04 +00:00
/**
* Take a string [first, last) which is a delimited list and add its
* elements into result as iterator pair. result is stored in out.
*/
template<typename InputIterator, typename OutputIterator>
OutputIterator splitIter
(InputIterator first,
InputIterator last,
OutputIterator out,
char delim,
bool doStrip = false,
bool allowEmpty = false)
{
for(InputIterator i = first; i != last;) {
InputIterator j = std::find(i, last, delim);
std::pair<InputIterator, InputIterator> p(i, j);
if(doStrip) {
p = stripIter(i, j);
}
if(allowEmpty || p.first != p.second) {
*out++ = p;
}
i = j;
if(j != last) {
++i;
}
}
if(allowEmpty &&
(first == last || *(last-1) == delim)) {
*out++ = std::make_pair(last, last);
}
return out;
}
template<typename InputIterator,
typename InputIterator2,
typename OutputIterator>
OutputIterator splitIterM
(InputIterator first,
InputIterator last,
OutputIterator out,
InputIterator2 dfirst,
InputIterator2 dlast,
bool doStrip = false,
bool allowEmpty = false)
{
for(InputIterator i = first; i != last;) {
InputIterator j = i;
for(; j != last && std::find(dfirst, dlast, *j) == dlast; ++j);
std::pair<InputIterator, InputIterator> p(i, j);
if(doStrip) {
p = stripIter(i, j);
}
if(allowEmpty || p.first != p.second) {
*out++ = p;
}
i = j;
if(j != last) {
++i;
}
}
if(allowEmpty &&
(first == last ||
std::find(dfirst, dlast, *(last-1)) != dlast)) {
*out++ = std::make_pair(last, last);
}
return out;
}
template<typename InputIterator, typename OutputIterator>
OutputIterator split
(InputIterator first,
InputIterator last,
OutputIterator out,
char delim,
bool doStrip = false,
bool allowEmpty = false)
{
for(InputIterator i = first; i != last;) {
InputIterator j = std::find(i, last, delim);
std::pair<InputIterator, InputIterator> p(i, j);
if(doStrip) {
p = stripIter(i, j);
}
if(allowEmpty || p.first != p.second) {
*out++ = std::string(p.first, p.second);
}
i = j;
if(j != last) {
++i;
}
}
if(allowEmpty &&
(first == last || *(last-1) == delim)) {
*out++ = std::string(last, last);
}
return out;
}
template<typename InputIterator1, typename InputIterator2>
bool streq
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2)
{
if(last1-first1 != last2-first2) {
return false;
}
return std::equal(first1, last1, first2);
}
template<typename InputIterator1, typename InputIterator2>
bool strieq
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2)
{
if(last1-first1 != last2-first2) {
return false;
}
for(; first1 != last1; ++first1, ++first2) {
char c1 = *first1;
char c2 = *first2;
if('A' <= c1 && c1 <= 'Z') {
c1 = c1-'A'+'a';
}
if('A' <= c2 && c2 <= 'Z') {
c2 = c2-'A'+'a';
}
if(c1 != c2) {
return false;
}
}
return true;
}
template<typename InputIterator1, typename InputIterator2>
bool startsWith
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2)
{
if(last1-first1 < last2-first2) {
return false;
}
return std::equal(first2, last2, first1);
}
2011-11-04 15:33:35 +00:00
template<typename InputIterator1, typename InputIterator2>
bool istartsWith
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2)
{
if(last1-first1 < last2-first2) {
return false;
}
return strieq(first1, first1+(last2-first2), first2, last2);
}
template<typename InputIterator1, typename InputIterator2>
bool endsWith
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2)
{
if(last1-first1 < last2-first2) {
return false;
}
return std::equal(first2, last2, last1-(last2-first2));
}
template<typename InputIterator1, typename InputIterator2>
bool iendsWith
(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2)
{
if(last1-first1 < last2-first2) {
return false;
}
2011-11-04 15:33:35 +00:00
return strieq(last1-(last2-first2), last1, first2, last2);
}
void generateRandomData(unsigned char* data, size_t length);
// Saves data to file whose name is filename. If overwrite is true,
// existing file is overwritten. Otherwise, this function doesn't do
// nothing. If data is saved successfully, return true. Otherwise
// returns false.
bool saveAs
(const std::string& filename, const std::string& data, bool overwrite=false);
// Prepend dir to relPath. If dir is empty, it prepends "." to relPath.
//
// dir = "/dir", relPath = "foo" => "/dir/foo"
// dir = "", relPath = "foo" => "./foo"
// dir = "/", relPath = "foo" => "/foo"
std::string applyDir(const std::string& dir, const std::string& relPath);
// In HTTP/FTP, file name is file component in URI. In HTTP, filename
// may be a value of Content-Disposition header. They are likely
// percent encoded. If they contains, for example, %2F, when decoded,
// basename contains dir component. This should be avoided. This
// function is created to fix these issues. This function expects src
// should be non-percent-encoded basename. Currently, this function
// replaces '/' with '_' and result string is passed to escapePath()
// function and its result is returned.
std::string fixTaintedBasename(const std::string& src);
// Generates 20 bytes random key and store it to the address pointed
// by key. Caller must allocate at least 20 bytes for generated key.
void generateRandomKey(unsigned char* key);
// Returns true is given numeric ipv4addr is in Private Address Space.
bool inPrivateAddress(const std::string& ipv4addr);
// Returns true if s contains directory traversal path component such
// as '..' or it contains null or control character which may fool
// user.
bool detectDirTraversal(const std::string& s);
// Replaces null(0x00) and control character(0x01-0x1f) with '_'. If
// __MINGW32__ is defined, following characters are also replaced with
// '_': '"', '*', ':', '<', '>', '?', '\', '|'.
std::string escapePath(const std::string& s);
// Returns true if ip1 and ip2 are in the same CIDR block. ip1 and
// ip2 must be numeric IPv4 or IPv6 address. If either of them or both
// of them is not valid numeric address, then returns false. bits is
// prefix bits. If bits is out of range, then bits is set to the
// length of binary representation of the address*8.
bool inSameCidrBlock
(const std::string& ip1, const std::string& ip2, size_t bits);
void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group);
void removeMetalinkContentTypes(RequestGroup* group);
2010-11-29 12:06:00 +00:00
// No throw
void executeHookByOptName
(const SharedHandle<RequestGroup>& group, const Option* option,
const Pref* pref);
2010-11-29 12:06:00 +00:00
// No throw
void executeHookByOptName
(const RequestGroup* group, const Option* option, const Pref* pref);
std::string createSafePath(const std::string& dir, const std::string& filename);
std::string encodeNonUtf8(const std::string& s);
// Create string safely. If str is NULL, returns empty string.
// Otherwise, returns std::string(str).
std::string makeString(const char* str);
// This function is basically the same with strerror(errNum) but when
// strerror returns NULL, this function returns empty string.
std::string safeStrerror(int errNum);
// Parses sequence [first, last) and find name=value pair delimited by
// delim character. If name(and optionally value) is found, returns
// pair of iterator which can use as first parameter of next call of
// this function, and true. If no name is found, returns the pair of
// last and false.
template<typename Iterator>
std::pair<Iterator, bool>
nextParam
(std::string& name,
std::string& value,
Iterator first,
Iterator last,
char delim)
{
Iterator end = last;
while(first != end) {
last = first;
Iterator parmnameFirst = first;
Iterator parmnameLast = first;
bool eqFound = false;
for(; last != end; ++last) {
if(*last == delim) {
break;
} else if(!eqFound && *last == '=') {
eqFound = true;
parmnameFirst = first;
parmnameLast = last;
}
}
std::pair<std::string::const_iterator,
std::string::const_iterator> namep;
std::pair<std::string::const_iterator,
std::string::const_iterator> valuep;
if(parmnameFirst == parmnameLast) {
if(!eqFound) {
parmnameFirst = first;
parmnameLast = last;
namep = stripIter(parmnameFirst, parmnameLast);
}
} else {
first = parmnameLast+1;
namep = stripIter(parmnameFirst, parmnameLast);
valuep = stripIter(first, last);
}
if(last != end) {
++last;
}
if(namep.first != namep.second) {
name.assign(namep.first, namep.second);
value.assign(valuep.first, valuep.second);
return std::make_pair(last, true);
}
first = last;
}
return std::make_pair(end, false);
}
template<typename T>
SharedHandle<T> copy(const SharedHandle<T>& a)
{
return SharedHandle<T>(new T(*a.get()));
}
// This is a bit different from cookie_helper::domainMatch(). If
// hostname is numeric host, then returns true if domain == hostname.
// That is if domain starts with ".", then returns true if domain is a
// suffix of hostname. If domain does not start with ".", then
// returns true if domain == hostname. Otherwise returns true.
// For example,
//
// * noProxyDomainMatch("aria2.sf.net", ".sf.net") returns true.
// * noProxyDomainMatch("sf.net", ".sf.net") returns false.
bool noProxyDomainMatch(const std::string& hostname, const std::string& domain);
} // namespace util
} // namespace aria2
#endif // D_UTIL_H