-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathClient.hs
More file actions
388 lines (329 loc) · 12.7 KB
/
Client.hs
File metadata and controls
388 lines (329 loc) · 12.7 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Distribution.Client
( -- * Command line handling
validateHackageURI
, validateHackageURI'
, validatePackageIds
-- * Fetching info from source and destination servers
, PkgIndexInfo(..)
, downloadIndex
, readNewIndex
-- * HTTP utilities
, HttpSession
, uriHostName
, httpSession
, Request
, mkRequest
, mkUploadRequest
, noRedirects
, applyBasicAuth
, runRequest
, Response(..)
, responseReadBSL
, requestGET'
, requestPUT
, (<//>)
, getETag
, checkStatus
) where
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import Network.HTTP.Types.Header
import Network.HTTP.Types.Status
import Network.HTTP.Types.Method
import Network.URI (URI(..), URIAuth(..), parseURI)
import Distribution.Server.Prelude
import Distribution.Client.UploadLog as UploadLog (read, Entry(..))
import Distribution.Client.Index as PackageIndex (read)
import Distribution.Server.Users.Types (UserId(..), UserName(UserName))
import Distribution.Server.Util.Merge
import Distribution.Server.Util.Parse (unpackUTF8)
import Distribution.Package
import Distribution.Verbosity
import Distribution.Simple.Utils
import Distribution.Text
import Control.Exception
import Control.Monad.Trans.Reader
import Data.Version
import Data.List
import Data.Time
import Data.Time.Clock.POSIX
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Char8 as BSS
import qualified Distribution.Server.Util.GZip as GZip
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import System.IO
import System.IO.Error
import System.FilePath
import System.Directory
import qualified System.FilePath.Posix as Posix
import Network.HTTP ()
-------------------------
-- Command line handling
-------------------------
validateHackageURI :: String -> Either String URI
validateHackageURI str = case parseURI str of
Nothing -> Left ("invalid URL " ++ str)
Just uri -> validateHackageURI' uri
validateHackageURI' :: URI -> Either String URI
validateHackageURI' uri
| not $ okayScheme (uriScheme uri) =
Left $ "only http URLs are supported " ++ show uri
| isNothing (uriAuthority uri) = Left $ "server name required in URL " ++ show uri
| otherwise = Right uri
where
okayScheme "http:" = True
okayScheme "https:" = True
okayScheme _ = False
validatePackageIds :: [String] -> Either String [PackageId]
validatePackageIds pkgstrs =
case theErrors of
theError : _ ->
Left $ "'" ++ theError ++ "' is not a valid package name or id"
_ -> Right pkgs
where
pkgstrs' = [ (pkgstr, simpleParse pkgstr) | pkgstr <- pkgstrs ]
pkgs = [ pkgid | (_, Just pkgid) <- pkgstrs' ]
theErrors = [ pkgstr | (pkgstr, Nothing) <- pkgstrs' ]
----------------------------------------------------
-- Fetching info from source and destination servers
----------------------------------------------------
data PkgIndexInfo = PkgIndexInfo
PackageId
(Maybe UTCTime) -- Upload time
(Maybe UserName) -- Name of uploader
(Maybe UserId) -- Id of uploader
deriving Show
downloadIndex :: URI -> FilePath -> HttpSession [PkgIndexInfo]
downloadIndex uri | isOldHackageURI uri = downloadOldIndex uri
| otherwise = downloadNewIndex uri
isOldHackageURI :: URI -> Bool
isOldHackageURI uri
| Just auth <- uriAuthority uri = uriRegName auth == "hackage.haskell.org"
| otherwise = False
downloadOldIndex :: URI -> FilePath -> HttpSession [PkgIndexInfo]
downloadOldIndex uri cacheDir = do
downloadFile indexURI indexFile
downloadFile logURI logFile
liftIO $ do
pkgids <- withFile indexFile ReadMode $ \hnd -> do
content <- BS.hGetContents hnd
case PackageIndex.read (\pkgid _ -> pkgid) (const True) (GZip.decompressNamed indexFile content) of
Right pkgs -> return pkgs
Left theError ->
dieNoVerbosity $ "Error parsing index at " ++ show uri ++ ": " ++ theError
theLog <- withFile logFile ReadMode $ \hnd -> do
content <- hGetContents hnd
case UploadLog.read content of
Right theLog -> return theLog
Left theError ->
dieNoVerbosity $ "Error parsing log at " ++ show uri ++ ": " ++ theError
return (mergeLogInfo pkgids theLog)
where
indexURI = uri <//> "packages" </> "archive" </> "00-index.tar.gz"
indexFile = cacheDir </> "00-index.tar.gz"
logURI = uri <//> "packages" </> "archive" </> "log"
logFile = cacheDir </> "log"
mergeLogInfo pkgids theLog =
mapMaybe selectDetails
$ mergeBy (\pkgid entry -> compare pkgid (entryPkgId entry))
(sort pkgids)
( map (maximumBy (comparing entryTime))
. groupBy (equating entryPkgId)
. sortBy (comparing entryPkgId)
$ theLog )
selectDetails (OnlyInRight _) = Nothing
selectDetails (OnlyInLeft pkgid) =
Just $ PkgIndexInfo pkgid Nothing Nothing Nothing
selectDetails (InBoth pkgid (UploadLog.Entry time uname _)) =
Just $ PkgIndexInfo pkgid (Just time) (Just uname) Nothing
entryPkgId (Entry _ _ pkgid) = pkgid
entryTime (Entry time _ _) = time
downloadNewIndex :: URI -> FilePath -> HttpSession [PkgIndexInfo]
downloadNewIndex uri cacheDir = do
downloadFile indexURI indexFile
readNewIndex cacheDir
where
indexURI = uri <//> "packages/00-index.tar.gz"
indexFile = cacheDir </> "00-index.tar.gz"
readNewIndex :: FilePath -> HttpSession [PkgIndexInfo]
readNewIndex cacheDir = do
liftIO $ withFile indexFile ReadMode $ \hnd -> do
content <- BS.hGetContents hnd
case PackageIndex.read selectDetails (const True) (GZip.decompressNamed indexFile content) of
Left theError ->
error ("Error parsing index at " ++ show indexFile ++ ": "
++ theError)
Right pkgs -> return pkgs
where
indexFile = cacheDir </> "00-index.tar.gz"
selectDetails :: PackageId -> Tar.Entry -> PkgIndexInfo
selectDetails pkgid entry =
PkgIndexInfo
pkgid
(Just time)
(if null username then Nothing else Just (UserName username))
(if userid == 0 then Nothing else Just (UserId userid))
where
time = epochTimeToUTC (Tar.entryTime entry)
username = Tar.ownerName (Tar.entryOwnership entry)
userid = Tar.ownerId (Tar.entryOwnership entry)
epochTimeToUTC :: Tar.EpochTime -> UTCTime
epochTimeToUTC = posixSecondsToUTCTime . realToFrac
-------------------------
-- HTTP utilities
-------------------------
infixr 5 <//>
(<//>) :: URI -> FilePath -> URI
uri <//> path = uri { uriPath = Posix.addTrailingPathSeparator (uriPath uri)
Posix.</> path }
uriHostName :: URI -> Maybe String
uriHostName = fmap uriRegName . uriAuthority
newtype HttpSession a = HttpSession (ReaderT HttpEnv IO a)
deriving (Functor, Applicative, Monad, MonadFail, MonadIO)
data HttpEnv = HttpEnv { httpManager :: Manager
, initialHeaders :: RequestHeaders
}
mkRequest
:: Method
-> RequestHeaders
-> URI
-> HttpSession Request
mkRequest meth headers uri = do
req0 <- liftIO $ requestFromURI uri
return $ req0 { method = meth, requestHeaders = headers }
mkUploadRequest
:: Method
-> URI
-> String -- ^ MIME type
-> Maybe String -- ^ encoding
-> RequestHeaders
-> ByteString -- ^ body
-> HttpSession Request
mkUploadRequest meth uri mimetype mEncoding headers body = do
req <- mkRequest meth (headers ++ headers') uri
return $ req { requestBody = RequestBodyLBS body }
where
headers' = [ (hContentLength, BSS.pack $ show (BS.length body))
, (hContentType, BSS.pack mimetype) ]
++ case mEncoding of
Nothing -> []
Just encoding -> [ (hContentEncoding, BSS.pack encoding) ]
-- | Prohibit following of redirects.
noRedirects :: Request -> Request
noRedirects req = req { redirectCount = 0 }
runRequest :: Request
-> (Response BodyReader -> IO a)
-> HttpSession a
runRequest req0 k = HttpSession $ do
env <- ask
let req = req0 { requestHeaders = initialHeaders env ++ requestHeaders req0 }
liftIO $ withResponse req (httpManager env) k
responseReadBSL :: Response BodyReader -> IO (Response BS.ByteString)
responseReadBSL rsp =
traverse (fmap BS.fromChunks . brConsume) rsp
httpSession :: Verbosity -> String -> Version -> HttpSession a -> IO a
httpSession _verbosity agent version (HttpSession action) = do
manager <- newTlsManager
let env = HttpEnv { httpManager = manager
, initialHeaders = [ (hUserAgent, BSS.pack $ agent ++ "/" ++ showVersion version) ]
}
runReaderT action env
downloadFile :: URI -> FilePath -> HttpSession ()
downloadFile uri file = do
liftIO $ putStrLn $ "downloading " ++ show uri ++ " to " ++ file
let etagFile = file <.> "etag"
metag <- liftIO $ catchJustDoesNotExistError
(Just <$> readFile etagFile)
(\_ -> return Nothing)
case metag of
Just etag -> do
let headers = [(hIfNoneMatch, BSS.pack (quote etag))]
req <- mkRequest "GET" headers uri
runRequest req $ \rsp -> do
case statusCode $ responseStatus rsp of
304 -> putStrLn $ file ++ " unchanged with ETag " ++ etag
200 -> writeDowloadedFileAndEtag rsp
_ -> do rsp' <- responseReadBSL rsp
hPutStrLn stderr (showFailure uri rsp')
Nothing -> do
req <- mkRequest "GET" [] uri
runRequest req $ \rsp ->
case statusCode $ responseStatus rsp of
200 -> writeDowloadedFileAndEtag rsp
_ -> do rsp' <- responseReadBSL rsp
hPutStrLn stderr (showFailure uri rsp')
where
writeDowloadedFileAndEtag rsp = do
bss <- brConsume (responseBody rsp)
BS.writeFile file (BS.fromChunks bss)
setETag file (unquote . BSS.unpack <$> lookup hETag (responseHeaders rsp))
getETag :: FilePath -> IO (Maybe String)
getETag file =
catchJustDoesNotExistError
(Just <$> readFile (file </> ".etag"))
(\_ -> return Nothing)
setETag :: FilePath -> Maybe String -> IO ()
setETag file Nothing = catchJustDoesNotExistError
(removeFile (file <.> "etag"))
(\_ -> return ())
setETag file (Just etag) = writeFile (file <.> "etag") etag
catchJustDoesNotExistError :: IO a -> (IOError -> IO a) -> IO a
catchJustDoesNotExistError =
catchJust (\e -> if isDoesNotExistError e then Just e else Nothing)
quote :: String -> String
quote s = '"' : s ++ ['"']
unquote :: String -> String
unquote ('"':s) = go s
where
go [] = []
go ('"':[]) = []
go (c:cs) = c : go cs
unquote s = s
-- | Like 'requestGET' but return @Nothing@ on 404 status.
requestGET' :: URI -> HttpSession (Maybe ByteString)
requestGET' uri = do
req <- mkRequest "GET" headers uri
runRequest req $ \rsp -> do
case statusCode $ responseStatus rsp of
404 -> return Nothing
_ -> do rsp' <- responseReadBSL rsp
checkStatus uri rsp'
return $ Just (responseBody rsp')
where
headers = []
requestPUT :: URI -> String -> Maybe String -> ByteString -> HttpSession ()
requestPUT uri mimetype mEncoding body = do
req <- mkUploadRequest "PUT" uri mimetype mEncoding [] body
runRequest req $ \rsp -> do
rsp' <- responseReadBSL rsp
checkStatus uri rsp'
checkStatus :: URI -> Response ByteString -> IO ()
checkStatus uri rsp = case statusCode $ responseStatus rsp of
-- 200 OK
200 -> return ()
-- 201 Created
201 -> return ()
-- 201 Created
202 -> return ()
-- 204 No Content
204 -> return ()
-- 400 Bad Request
400 -> liftIO (warn normal (showFailure uri rsp)) >> return ()
-- Other
_code -> fail (showFailure uri rsp)
showFailure :: URI -> Response ByteString -> String
showFailure uri rsp = unlines
[ "error: failed HTTP request"
, " status: " ++ show (responseStatus rsp)
, " url: " ++ show uri
, " response: " ++
case lookup hContentType (responseHeaders rsp) of
Just mimetype | "text/plain" `BSS.isPrefixOf` mimetype
-> '\n' : (unpackUTF8 . responseBody $ rsp)
_ -> ""
]