OSDN Git Service

Implement package installer for tar archives.
[mingw/mingw-get.git] / src / pkginet.cpp
1 /*
2  * pkginet.cpp
3  *
4  * $Id$
5  *
6  * Written by Keith Marshall <keithmarshall@users.sourceforge.net>
7  * Copyright (C) 2009, 2010, MinGW Project
8  *
9  *
10  * Implementation of the package download machinery for mingw-get.
11  *
12  *
13  * This is free software.  Permission is granted to copy, modify and
14  * redistribute this software, under the provisions of the GNU General
15  * Public License, Version 3, (or, at your option, any later version),
16  * as published by the Free Software Foundation; see the file COPYING
17  * for licensing details.
18  *
19  * Note, in particular, that this software is provided "as is", in the
20  * hope that it may prove useful, but WITHOUT WARRANTY OF ANY KIND; not
21  * even an implied WARRANTY OF MERCHANTABILITY, nor of FITNESS FOR ANY
22  * PARTICULAR PURPOSE.  Under no circumstances will the author, or the
23  * MinGW Project, accept liability for any damages, however caused,
24  * arising from the use of this software.
25  *
26  */
27 #define WIN32_LEAN_AND_MEAN
28
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <wininet.h>
33 #include <errno.h>
34
35 #include "dmh.h"
36 #include "mkpath.h"
37
38 #include "pkgbase.h"
39 #include "pkgkeys.h"
40 #include "pkgtask.h"
41
42 class pkgInternetAgent
43 {
44   /* A minimal, locally implemented class, instantiated ONCE as a
45    * global object, to ensure that wininet's global initialisation is
46    * completed at the proper time, without us doing it explicitly.
47    */
48   private:
49     HINTERNET SessionHandle;
50
51   public:
52     inline pkgInternetAgent():SessionHandle( NULL )
53     {
54       /* Constructor...
55        */
56       if( InternetAttemptConnect( 0 ) == ERROR_SUCCESS )
57         SessionHandle = InternetOpen
58           ( "MinGW Installer", INTERNET_OPEN_TYPE_PRECONFIG,
59              NULL, NULL, 0
60           );
61     }
62     inline ~pkgInternetAgent()
63     {
64       /* Destructor...
65        */
66       if( SessionHandle != NULL )
67         Close( SessionHandle );
68     }
69
70     /* Remaining methods are simple inline wrappers for the
71      * wininet functions we plan to use...
72      */
73     inline HINTERNET OpenURL( const char *URL )
74     {
75       return InternetOpenUrl( SessionHandle, URL, NULL, 0, 0, 0 );
76     }
77     inline DWORD QueryStatus( HINTERNET id )
78     {
79       DWORD ok, idx = 0, len = sizeof( ok );
80       if( HttpQueryInfo( id, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &ok, &len, &idx ) )
81         return ok;
82       return 0;
83     }
84     inline int Read( HINTERNET dl, char *buf, size_t max, DWORD *count )
85     {
86       return InternetReadFile( dl, buf, max, count );
87     }
88     inline int Close( HINTERNET id )
89     {
90       return InternetCloseHandle( id );
91     }
92 };
93
94 /* This is the one and only instantiation of an object of this class.
95  */
96 static pkgInternetAgent pkgDownloadAgent;
97
98 class pkgInternetStreamingAgent
99 {
100   /* Another locally implemented class; each individual file download
101    * gets its own instance of this, either as-is for basic data transfer,
102    * or as a specialised derivative of this base class.
103    */
104   protected:
105     const char *filename;
106     const char *dest_template;
107
108     char *dest_file;
109     HINTERNET dl_host;
110     int dl_status;
111
112   private:
113     virtual int TransferData( int );
114
115   public:
116     pkgInternetStreamingAgent( const char*, const char* );
117     virtual ~pkgInternetStreamingAgent();
118
119     virtual int Get( const char* );
120     inline const char *DestFile(){ return dest_file; }
121 };
122
123 pkgInternetStreamingAgent::pkgInternetStreamingAgent
124 ( const char *local_name, const char *dest_specification )
125 {
126   /* Constructor for the pkgInternetStreamingAgent class.
127    */
128   filename = local_name;
129   dest_template = dest_specification;
130   dest_file = (char *)(malloc( mkpath( NULL, dest_template, filename, NULL ) ));
131   if( dest_file != NULL )
132     mkpath( dest_file, dest_template, filename, NULL );
133 }
134
135 pkgInternetStreamingAgent::~pkgInternetStreamingAgent()
136 {
137   /* Destructor needs to free the heap memory allocated by the
138    * constructor, for storage of "dest_file" name.
139    */
140   free( (void *)(dest_file) );
141 }
142
143 int pkgInternetStreamingAgent::TransferData( int fd )
144 {
145   /* In the case of this base class implementation,
146    * we simply read the file's data from the Internet source,
147    * and write a verbatim copy to the destination file.
148    */
149   char buf[8192]; DWORD count, tally = 0;
150   do { dl_status = pkgDownloadAgent.Read( dl_host, buf, sizeof( buf ), &count );
151        dmh_printf( "\rdownloading: %s: %I32d b", filename, tally += count );
152        write( fd, buf, count );
153      } while( dl_status && (count > 0) );
154   dmh_printf( "\rdownloading: %s: %I32d b\n", filename, tally );
155   return dl_status;
156 }
157
158 static const char *get_host_info
159 ( pkgXmlNode *ref, const char *property, const char *fallback = NULL )
160 {
161   /* Helper function to retrieve host information from the XML catalogue.
162    *
163    * Call with property = "url", to retrieve the URL template to pass as
164    * "fmt" argument to mkpath(), or with property = "mirror", to retrieve
165    * the substitution text for the "modifier" argument.
166    */
167   const char *uri = NULL;
168   while( ref != NULL )
169   {
170     /* Starting from the "ref" package entry in the catalogue...
171      */
172     pkgXmlNode *host = ref->FindFirstAssociate( download_host_key );
173     while( host != NULL )
174     {
175       /* Examine its associate tags; if we find one of type
176        * "download-host", with the requisite property, then we
177        * immediately return that property value...
178        */
179       if( (uri = host->GetPropVal( property, NULL )) != NULL )
180         return uri;
181
182       /* Otherwise, we look for any other candidate tags
183        * associated with the same catalogue entry...
184        */
185       host = host->FindNextAssociate( download_host_key );
186     }
187     /* Failing an immediate match, extend the search to the
188      * ancestors of the initial reference entry...
189      */
190     ref = ref->GetParent();
191   }
192   /* ...and ultimately, if no match is found, we return the
193    * specified "fallback" property value.
194    */
195   return fallback;
196 }
197
198 static inline
199 int set_transit_path( const char *path, const char *file, char *buf = NULL )
200 {
201   /* Helper to define the transitional path name for downloaded files,
202    * used to save the file data while the download is in progress.
203    */
204   static const char *transit_dir = "/.in-transit";
205   return mkpath( buf, path, file, transit_dir );
206 }
207
208 int pkgInternetStreamingAgent::Get( const char *from_url )
209 {
210   /* Download a file from the specified internet URL.
211    *
212    * Before download commences, we accept that this may fail...
213    */
214   dl_status = 0;
215
216   /* Set up a "transit-file" to receive the downloaded content.
217    */
218   char transit_file[set_transit_path( dest_template, filename )];
219   int fd; set_transit_path( dest_template, filename, transit_file );
220
221   if( (fd = set_output_stream( transit_file, 0644 )) >= 0 )
222   {
223     /* The "transit-file" is ready to receive incoming data...
224      * Configure and invoke the download handler to copy the data
225      * from the appropriate host URL, to this "transit-file".
226      */
227     if( (dl_host = pkgDownloadAgent.OpenURL( from_url )) != NULL )
228     {
229       if( pkgDownloadAgent.QueryStatus( dl_host ) == HTTP_STATUS_OK )
230       {
231         /* With the download transaction fully specified, we may
232          * request processing of the file transfer...
233          */
234         dl_status = TransferData( fd );
235       }
236
237       /* We are done with the URL handle; close it.
238        */
239       pkgDownloadAgent.Close( dl_host );
240     }
241
242     /* Always close the "transit-file", whether the download
243      * was successful, or not...
244      */
245     close( fd );
246     if( dl_status )
247       /*
248        * When successful, we move the "transit-file" to its
249        * final downloaded location...
250        */
251       rename( transit_file, dest_file );
252     else
253       /* ...otherwise, we discard the incomplete "transit-file",
254        * leaving the caller to diagnose the failure.
255        */
256       unlink( transit_file );
257   }
258
259   /* Report success or failure to the caller...
260    */
261   return dl_status;
262 }
263
264 void pkgActionItem::DownloadArchiveFiles( pkgActionItem *current )
265 {
266   /* Update the local package cache, to ensure that all packages needed
267    * to complete the current set of scheduled actions are present; if any
268    * are missing, invoke an Internet download agent to fetch them.  This
269    * requires us to walk the action list...
270    */
271   while( current != NULL )
272   {
273     /* ...while we haven't run off the end...
274      */
275     if( (current->flags & ACTION_INSTALL) == ACTION_INSTALL )
276     {
277       /* For all packages specified in the current action list,
278        * for which an "install" action is scheduled, and for which
279        * no associated archive file is present in the local archive
280        * cache, place an Internet download agent on standby to fetch
281        * the required archive from a suitable internet mirror host.
282        */
283       const char *package_name = current->Selection()->ArchiveName();
284       pkgInternetStreamingAgent download( package_name, pkgArchivePath() );
285
286       /* Check if the required archive is already available locally...
287        */
288       if( (access( download.DestFile(), R_OK ) != 0) && (errno == ENOENT) )
289       {
290         /* ...if not, ask the download agent to fetch it...
291          */
292         const char *url_template = get_host_info( current->Selection(), uri_key );
293         if( url_template != NULL )
294         {
295           /* ...from the URL constructed from the template specified in
296            * the package repository catalogue (configuration database)...
297            */
298           const char *mirror = get_host_info( current->Selection(), mirror_key );
299           char package_url[mkpath( NULL, url_template, package_name, mirror )];
300           mkpath( package_url, url_template, package_name, mirror );
301           if( ! (download.Get( package_url ) > 0) )
302             dmh_notify( DMH_ERROR,
303                 "Get package: %s: download failed\n", package_url
304               );
305         }
306         else
307           /* Cannot download; the repository catalogue didn't specify a
308            * template, from which to construct a download URL...
309            */
310           dmh_notify( DMH_ERROR,
311               "Get package: %s: no URL specified for download\n", package_name
312             );
313       }
314     }
315     /* Repeat download action, for any additional packages specified
316      * in the current "actions" list.
317      */
318     current = current->next;
319   }
320 }
321
322 #define DATA_CACHE_PATH         "%R" "var/cache/mingw-get/data"
323 #define WORKING_DATA_PATH       "%R" "var/lib/mingw-get/data"
324
325 /* Internet servers host package catalogues in lzma compressed format;
326  * we will decompress them "on the fly", as we download them.  To achieve
327  * this, we will use a variant of the pkgInternetStreamingAgent, using a
328  * specialised TransferData method; additionally, this will incorporate
329  * a special derivative of a pkgLzmaArchiveStream, with its GetRawData
330  * method adapted to stream data from an internet URI, instead of
331  * reading from a local file.
332  *
333  * To derive the pkgInternetLzmaStreamingAgent, we need to include the
334  * specialised declarations of a pkgArchiveStream, in order to make the
335  * declaration of pkgLzmaArchiveStream available as our base class.
336  */
337 #define  PKGSTRM_H_SPECIAL  1
338 #include "pkgstrm.h"
339
340 class pkgInternetLzmaStreamingAgent :
341 public pkgInternetStreamingAgent, public pkgLzmaArchiveStream
342 {
343   /* Specialisation of the pkgInternetStreamingAgent base class,
344    * providing decompressed copies of LZMA encoded files downloaded
345    * from the Internet; (the LZMA decompression capability is derived
346    * from the pkgLzmaArchiveStream base class).
347    */
348   public:
349     /* We need a specialised constructor...
350      */
351     pkgInternetLzmaStreamingAgent( const char*, const char* );
352
353   private:
354     /* Specialisation requires overrides for each of this pair of
355      * methods, (the first from the pkgLzmaArchiveStream base class;
356      * the second from pkgInternetStreamingAgent).
357      */
358     virtual int GetRawData( int, uint8_t*, size_t );
359     virtual int TransferData( int );
360 };
361
362 /* This specialisation of the pkgInternetStreamingAgent class needs its
363  * own constructor, simply to invoke the constructors for the base classes,
364  * (since neither is instantiated by a default constructor).
365  */
366 pkgInternetLzmaStreamingAgent::pkgInternetLzmaStreamingAgent
367 ( const char *local_name, const char *dest_specification ):
368 pkgInternetStreamingAgent( local_name, dest_specification ),
369 /*
370  * Note that, when we come to initialise the lzma streaming component
371  * of this derived class, we will be streaming directly from the internet,
372  * rather than from a file stream, so we don't require a file descriptor
373  * for the input stream; however, the class semantics still expect one.
374  * To avoid accidental association with an existing file stream, we
375  * use a negative value, (which is never a valid file descriptor);
376  * however, we must not choose -1, since the class implementation
377  * will decline to process the stream; hence, we choose -2.
378  */
379 pkgLzmaArchiveStream( -2 ){}
380
381 int pkgInternetLzmaStreamingAgent::GetRawData( int fd, uint8_t *buf, size_t max )
382 {
383   /* Fetch raw (compressed) data from the Internet host, and load it into
384    * the decompression filter's input buffer, whence the TransferData routine
385    * may retrieve it, via the filter, as an uncompressed stream.
386    */
387   DWORD count;
388   dl_status = pkgDownloadAgent.Read( dl_host, (char *)(buf), max, &count );
389   return (int)(count);
390 }
391
392 int pkgInternetLzmaStreamingAgent::TransferData( int fd )
393 {
394   /* In this case, we read the file's data from the Internet source,
395    * stream it through the lzma decompression filter, and write a copy
396    * of the resultant decompressed data to the destination file.
397    */
398   char buf[8192]; DWORD count;
399   do { count = pkgLzmaArchiveStream::Read( buf, sizeof( buf ) );
400        write( fd, buf, count );
401      } while( dl_status && (count > 0) );
402   return dl_status;
403 }
404
405 static const char *serial_number( const char *catalogue )
406 {
407   /* Local helper function to retrieve issue numbers from any repository
408    * package catalogue; returns the result as a duplicate of the internal
409    * string, allocated on the heap (courtesy of the strdup() function).
410    */
411   const char *issue;
412   pkgXmlDocument src( catalogue );
413
414   if(   src.IsOk()
415   &&  ((issue = src.GetRoot()->GetPropVal( issue_key, NULL )) != NULL)  )
416     /*
417      * Found an issue number; return a copy...
418      */
419     return strdup( issue );
420
421   /* If we get to here, we couldn't get a valid issue number;
422    * whatever the reason, return NULL to indicate failure.
423    */
424   return NULL;
425 }
426
427 void pkgXmlDocument::SyncRepository( const char *name, pkgXmlNode *repository )
428 {
429   /* Fetch a named package catalogue from a specified Internet repository.
430    *
431    * Package catalogues are XML files; the master copy on the Internet host
432    * must be stored in lzma compressed format, and named to comply with the
433    * convention "%F.xml.lzma", in which "%F" represents the value of the
434    * "name" argument passed to this pkgXmlDocument class method.
435    */ 
436   const char *url_template;
437   if( (url_template = repository->GetPropVal( uri_key, NULL )) != NULL )
438   {
439     /* Initialise a streaming agent, to manage the catalogue download;
440      * (note that we must include the "%/M" placeholder in the template
441      * for the local name, to accommodate the name of the intermediate
442      * "in-transit" directory used by the streaming agent).
443      */
444     pkgInternetLzmaStreamingAgent download( name, DATA_CACHE_PATH "%/M/%F.xml" );
445     {
446       /* Construct the full URI for the master catalogue, and stream it to
447        * a locally cached, decompressed copy of the XML file.
448        */
449       const char *mirror = repository->GetPropVal( mirror_key, NULL );
450       char catalogue_url[mkpath( NULL, url_template, name, mirror )];
451       mkpath( catalogue_url, url_template, name, mirror );
452       if( download.Get( catalogue_url ) <= 0 )
453         dmh_notify( DMH_ERROR,
454             "Sync Repository: %s: download failed\n", catalogue_url
455           );
456     }
457
458     /* We will only replace our current working copy of this catalogue,
459      * (if one already exists), with the copy we just downloaded, if this
460      * downloaded copy bears an issue number indicating that it is more
461      * recent than the working copy.
462      */
463     const char *repository_version, *working_version;
464     if( (repository_version = serial_number( download.DestFile() )) != NULL )
465     {
466       /* Identify the location for the working copy, (if it exists).
467        */
468       const char *working_copy_path_name = WORKING_DATA_PATH "/%F.xml";
469       char working_copy[mkpath( NULL, working_copy_path_name, name, NULL )];
470       mkpath( working_copy, working_copy_path_name, name, NULL );
471
472       /* Compare issue serial numbers...
473        */
474       if( ((working_version = serial_number( working_copy )) == NULL)
475       ||  ((strcmp( repository_version, working_version )) > 0)        )
476       {
477         /* In these circumstances, we couldn't identify an issue number
478          * for the working copy of the catalogue; (maybe there is no such
479          * catalogue, or maybe it doesn't specify a valid issue number);
480          * in either case, we promote the downloaded copy in its place.
481          *
482          * FIXME: we assume that the working file and the downloaded copy
483          * are stored on the same physical file system device, so we may
484          * replace the former by simply deleting it, and renaming the
485          * latter with its original path name; we make no provision for
486          * replacing the working version by physical data copying.
487          */
488         unlink( working_copy );
489         rename( download.DestFile(), working_copy );
490       }
491
492       /* The issue numbers, returned by the serial_number() function, were
493        * allocated on the heap; free them to avoid leaking memory!
494        */
495       free( (void *)(repository_version) );
496       /*
497        * The working copy issue number may be represented by a NULL pointer;
498        * while it may be safe to call free on this, it just *seems* wrong, so
499        * we check it first, to be certain.
500        */
501       if( working_version != NULL )
502         free( (void *)(working_version) );
503     }
504
505     /* If the downloaded copy of the catalogue is still in the download cache,
506      * we have chosen to keep a previous working copy, so we have no further
507      * use for the downloaded copy; discard it, noting that we don't need to
508      * confirm its existence because this will fail silently, if it is no
509      * longer present.
510      */
511     unlink( download.DestFile() );
512   }
513 }
514
515 /* $RCSfile$: end of file */