summaryrefslogtreecommitdiff
path: root/src/Data/Torrent.hs
blob: 36b9de502144c53fe99e229b5d3c4de4ac59ca09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
-- |
--   Copyright   :  (c) Sam Truzjan 2013
--   License     :  BSD3
--   Maintainer  :  pxqr.sta@gmail.com
--   Stability   :  experimental
--   Portability :  portable
--
--   Torrent file contains metadata about files and folders but not
--   content itself. The files are bencoded dictionaries. There is
--   also other info which is used to help join the swarm.
--
--   This module provides torrent metainfo serialization and info hash
--   extraction.
--
--   For more info see:
--   <http://www.bittorrent.org/beps/bep_0003.html#metainfo-files>,
--   <https://wiki.theory.org/BitTorrentSpecification#Metainfo_File_Structure>
--
{-# LANGUAGE CPP                        #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE BangPatterns               #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable         #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# OPTIONS -fno-warn-orphans           #-}
module Data.Torrent
       ( -- * Info dictionary
         InfoDict (..)
       , infohash
       , layoutInfo
       , pieceInfo
       , isPrivate

         -- * Torrent file
       , Torrent(..)
       , announce
       , announceList
       , comment
       , createdBy
       , creationDate
       , encoding
       , infoDict
       , publisher
       , publisherURL
       , signature

       , nullTorrent

         -- * IO
       , torrentExt
       , isTorrentPath
       , fromFile
       , toFile
       ) where

import Prelude hiding (sum)

import Control.Applicative
import Control.DeepSeq
import Control.Exception
import Control.Lens

import Data.Aeson.Types (ToJSON(..), FromJSON(..), Value(..), withText)
import Data.Aeson.TH
import Data.BEncode as BE
import Data.BEncode.Types as BE
import           Data.ByteString as BS
import qualified Data.ByteString.Char8 as BC (pack, unpack)
import qualified Data.ByteString.Lazy  as BL
import           Data.Char as Char
import           Data.Hashable   as Hashable
import qualified Data.List as L
import           Data.Text as T
import Data.Time
import Data.Time.Clock.POSIX
import Data.Typeable
import Network.URI
import System.FilePath

import Data.Torrent.InfoHash as IH
import Data.Torrent.Layout
import Data.Torrent.Piece


{-----------------------------------------------------------------------
--  Info dictionary
-----------------------------------------------------------------------}

{- note that info hash is actually reduntant field
   but it's better to keep it here to avoid heavy recomputations
-}

-- | Info part of the .torrent file contain info about each content file.
data InfoDict = InfoDict
  { idInfoHash     :: !InfoHash
      -- ^ SHA1 hash of the (other) 'DictInfo' fields.
  , idLayoutInfo   :: !LayoutInfo
  , idPieceInfo    :: !PieceInfo
  , idPrivate      :: !Bool
    -- ^ If set the client MUST publish its presence to get other
    -- peers ONLY via the trackers explicity described in the
    -- metainfo file.
    --
    --   BEP 27: <http://www.bittorrent.org/beps/bep_0027.html>
  } deriving (Show, Read, Eq, Typeable)

$(deriveJSON (L.map Char.toLower . L.dropWhile isLower) ''InfoDict)

makeLensesFor
  [ ("idInfoHash"  , "infohash"  )
  , ("idLayoutInfo", "layoutInfo")
  , ("idPieceInfo" , "pieceInfo" )
  , ("idPrivate"   , "isPrivate" )
  ]
  ''InfoDict

instance NFData InfoDict where
  rnf InfoDict {..} = rnf idLayoutInfo

instance Hashable InfoDict where
  hash = Hashable.hash . idInfoHash
  {-# INLINE hash #-}

getPrivate :: Get Bool
getPrivate = (Just True ==) <$>? "private"

putPrivate :: Bool -> BDict -> BDict
putPrivate False = id
putPrivate True  = \ cont -> "private" .=! True .: cont

instance BEncode InfoDict where
  toBEncode InfoDict {..} = toDict $
      putLayoutInfo idLayoutInfo   $
      putPieceInfo  idPieceInfo    $
      putPrivate    idPrivate      $
      endDict

  fromBEncode dict = (`fromDict` dict) $ do
      InfoDict ih <$> getLayoutInfo
                  <*> getPieceInfo
                  <*> getPrivate
    where
      ih = IH.hashlazy (encode dict)

{-----------------------------------------------------------------------
--  Torrent info
-----------------------------------------------------------------------}

-- | Metainfo about particular torrent.
data Torrent = Torrent
  { tAnnounce     :: !URI
    -- ^ The URL of the tracker.

  , tAnnounceList :: !(Maybe [[URI]])
    -- ^ Announce list add multiple tracker support.
    --
    --   BEP 12: <http://www.bittorrent.org/beps/bep_0012.html>

  , tComment      :: !(Maybe Text)
    -- ^ Free-form comments of the author.

  , tCreatedBy    :: !(Maybe Text)
    -- ^ Name and version of the program used to create the .torrent.

  , tCreationDate :: !(Maybe POSIXTime)
    -- ^ Creation time of the torrent, in standard UNIX epoch.

  , tEncoding     :: !(Maybe Text)
    -- ^ String encoding format used to generate the pieces part of
    --   the info dictionary in the .torrent metafile.

  , tInfoDict     :: !InfoDict
    -- ^ Info about each content file.

  , tPublisher    :: !(Maybe URI)
    -- ^ Containing the RSA public key of the publisher of the
    -- torrent.  Private counterpart of this key that has the
    -- authority to allow new peers onto the swarm.

  , tPublisherURL :: !(Maybe URI)
  , tSignature    :: !(Maybe ByteString)
    -- ^ The RSA signature of the info dictionary (specifically, the
    --   encrypted SHA-1 hash of the info dictionary).
    } deriving (Show, Eq, Typeable)

instance FromJSON URI where
  parseJSON = withText "URI" $
    maybe (fail "could not parse URI") pure . parseURI . T.unpack

instance ToJSON URI where
  toJSON = String . T.pack . show

instance ToJSON NominalDiffTime where
  toJSON = toJSON . posixSecondsToUTCTime

instance FromJSON NominalDiffTime where
  parseJSON v = utcTimeToPOSIXSeconds <$> parseJSON v

$(deriveToJSON (L.map Char.toLower . L.dropWhile isLower) ''Torrent)

makeLensesFor
  [ ("tAnnounce"    , "announce"    )
  , ("tAnnounceList", "announceList")
  , ("tComment"     , "comment"     )
  , ("tCreatedBy"   , "createdBy"   )
  , ("tCreationDate", "creationDate")
  , ("tEncoding"    , "encoding"    )
  , ("tInfoDict"    , "infoDict"    )
  , ("tPublisher"   , "publisher"   )
  , ("tPublisherURL", "publisherURL")
  , ("tSignature"   , "signature"   )
  ]
  ''Torrent

instance NFData Torrent where
  rnf Torrent {..} = rnf tInfoDict

-- TODO move to bencoding
instance BEncode URI where
  toBEncode uri = toBEncode (BC.pack (uriToString id uri ""))
  {-# INLINE toBEncode #-}

  fromBEncode (BString s) | Just url <- parseURI (BC.unpack s) = return url
  fromBEncode b           = decodingError $ "url <" ++ show b ++ ">"
  {-# INLINE fromBEncode #-}

-- TODO move to bencoding
instance BEncode POSIXTime where
  toBEncode pt = toBEncode (floor pt :: Integer)
  fromBEncode (BInteger i) = return $ fromIntegral i
  fromBEncode _            = decodingError $ "POSIXTime"

instance BEncode Torrent where
  toBEncode Torrent {..} = toDict $
       "announce"      .=! tAnnounce
    .: "announce-list" .=? tAnnounceList
    .: "comment"       .=? tComment
    .: "created by"    .=? tCreatedBy
    .: "creation date" .=? tCreationDate
    .: "encoding"      .=? tEncoding
    .: "info"          .=! tInfoDict
    .: "publisher"     .=? tPublisher
    .: "publisher-url" .=? tPublisherURL
    .: "signature"     .=? tSignature
    .: endDict

  fromBEncode = fromDict $ do
    Torrent <$>! "announce"
            <*>? "announce-list"
            <*>? "comment"
            <*>? "created by"
            <*>? "creation date"
            <*>? "encoding"
            <*>! "info"
            <*>? "publisher"
            <*>? "publisher-url"
            <*>? "signature"

-- | A simple torrent contains only required fields.
nullTorrent :: URI -> InfoDict -> Torrent
nullTorrent ann info = Torrent
    ann  Nothing Nothing Nothing Nothing Nothing
    info Nothing Nothing Nothing

-- | Extension usually used for torrent metafiles.
torrentExt :: String
torrentExt = "torrent"

-- | Test if this path has proper extension.
isTorrentPath :: FilePath -> Bool
isTorrentPath filepath = takeExtension filepath == extSeparator : torrentExt

-- | Read and decode a .torrent file.
fromFile :: FilePath -> IO Torrent
fromFile filepath = do
  contents <- BS.readFile filepath
  case decode contents of
    Right !t -> return t
    Left msg -> throwIO $ userError $ msg ++ " while reading torrent file"

toFile :: FilePath -> Torrent -> IO ()
toFile filepath = BL.writeFile filepath . encode