OSDN Git Service

Support group affiliation with component package granularity.
[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-2013, MinGW.org 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 USES_SAFE_STRCMP  1
28 #define WIN32_LEAN_AND_MEAN
29
30 #define _WIN32_WINNT 0x0500     /* for GetConsoleWindow() kludge */
31 #include <windows.h>
32 /*
33  * FIXME: This kludge allows us to use the standard wininet dialogue
34  * to acquire proxy authentication credentials from the user; this is
35  * expedient for now, (if somewhat anti-social for a CLI application).
36  * We will ultimately need to provide a more robust implementation,
37  * (within the scope of the diagnostic message handler), in order to
38  * obtain a suitable window handle for use when called from the GUI
39  * implementation of mingw-get, (when it becomes available).
40  */
41 #define dmh_dialogue_context()  GetConsoleWindow()
42
43 #include <sys/stat.h>
44
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <wininet.h>
49 #include <errno.h>
50
51 #include "dmh.h"
52 #include "mkpath.h"
53 #include "debug.h"
54
55 #include "pkgbase.h"
56 #include "pkginet.h"
57 #include "pkgkeys.h"
58 #include "pkgtask.h"
59
60 /* This static member variable of the pkgDownloadMeter class
61  * provides a mechanism for communicating with a pre-existing
62  * download monitoring dialogue, such as is employed in the GUI.
63  * We MUST define it, and we also initialise it to NULL.  While
64  * it remains thus, (as it always does in the CLI), no attempt
65  * will be made to access any pre-existing dialogue, and local
66  * monitoring objects will be employed; the GUI sets this to
67  * refer to its dialogue, when this is activated.
68  */
69 pkgDownloadMeter *pkgDownloadMeter::primary = NULL;
70
71 inline void pkgDownloadMeter::SpinWait( int mode, const char *uri )
72 {
73   /* Wrapper to invoke the overridable derived class specific
74    * SpinWait() method, with protection against any attempt to
75    * access a virtual method of a primary class object which
76    * does not exist; (thus, there is no vtable reference).
77    */
78   if( primary != NULL ) primary->SpinWaitAction( mode, uri );
79 }
80
81 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
82
83 /* Implementation of a download meter class, displaying download
84  * statistics within a CLI application context.
85  */
86 class pkgDownloadMeterTTY: public pkgDownloadMeter
87 {
88   public:
89     pkgDownloadMeterTTY( const char*, unsigned long );
90     virtual ~pkgDownloadMeterTTY();
91
92     virtual int Update( unsigned long );
93
94   private:
95     /* This buffer is used to store each compiled status report,
96      * in preparation for display on the console.
97      */
98     const char *source_url;
99     char status_report[80];
100 };
101
102 /* Constructor...
103  */
104 pkgDownloadMeterTTY::pkgDownloadMeterTTY( const char *url, unsigned long length ):
105   source_url( url ){ content_length = length; }
106
107 /* ...and destructor.
108  */
109 pkgDownloadMeterTTY::~pkgDownloadMeterTTY()
110 {
111   if( source_url == NULL )
112     dmh_printf( "\n" );
113 }
114
115 #elif IMPLEMENTATION_LEVEL == SETUP_TOOL_COMPONENT
116
117 /* The setup tool will always use GUI style download metering;
118  * however the download agent remains CLI capable, so we need a
119  * minimal "do nothing" implementation of a TTY style metering
120  * class, to satisfy the linker.
121  */
122 class pkgDownloadMeterTTY: public pkgDownloadMeter
123 {
124   /* Implementation of a dummy download meter class, sufficient
125    * to promote an illusion of TTY metering capability.
126    */
127   public:
128     pkgDownloadMeterTTY( const char*, unsigned long ){}
129     virtual int Update( unsigned long ){ return 0; }
130 };
131
132 #endif
133
134 static inline __attribute__((__always_inline__))
135 unsigned long pow10mul( register unsigned long x, unsigned power )
136 {
137   /* Inline helper to perform a fast integer multiplication of "x"
138    * by a specified power of ten.
139    */
140   while( power-- )
141   {
142     /* Each cycle multiplies by ten, first shifting to get "x * 2"...
143      */
144     x <<= 1;
145     /*
146      * ...then further shifting that intermediate result, and adding,
147      * to achieve the effect of "x * 2 + x * 2 * 4".
148      */
149     x += (x << 2);
150   }
151   return x;
152 }
153
154 static inline __attribute__((__always_inline__))
155 unsigned long percentage( unsigned long x, unsigned long q )
156 {
157   /* Inline helper to compute "x" as an integer percentage of "q".
158    */
159   return pow10mul( x, 2 ) / q;
160 }
161
162 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
163
164 int pkgDownloadMeterTTY::Update( unsigned long count )
165 {
166   /* Implementation of method to update the download progress report,
167    * displaying the current byte count and anticipated final byte count,
168    * each formatted in a conveniently human readable style, followed by
169    * approximate percentage completion, both as a 48-segment bar graph,
170    * and as a numeric tally.
171    */
172   char *p = status_report;
173   int barlen = (content_length > count)
174     ? (((count << 1) + count) << 4) / content_length
175     : (content_length > 0) ? 48 : 0;
176
177   /* We may safely use sprintf() to assemble the status report, because
178    * we control the field lengths to always fit within the buffer.
179    */
180   p += SizeFormat( p, count );
181   p += sprintf( p, " / " );
182   p += (content_length > 0)
183     ? SizeFormat( p, content_length )
184     : sprintf( p, "????.?? ??" );
185   p += sprintf( p, "%*c", status_report + 25 - p, '|' ); p[barlen] = '\0';
186   p += sprintf( p, "%-48s", (char *)(memset( p, '=', barlen )) );
187   p += ( (content_length > 0) && (content_length >= count) )
188     ? sprintf( p, "|%4lu", percentage( count, content_length ) )
189     : sprintf( p, "| ???" );
190
191   if( source_url != NULL )
192   {
193     dmh_printf( "%s\n", source_url );
194     source_url = NULL;
195   }
196   return dmh_printf( "\r%s%%", status_report );
197 }
198
199 #endif
200
201 int pkgDownloadMeter::SizeFormat( char *buf, unsigned long filesize )
202 {
203   /* Helper method to format raw byte counts as B, kB, MB, GB, TB, as
204    * appropriate; (this NEVER requires more than ten characters).
205    */
206   int retval;
207   const unsigned long sizelimit = 1 << 10; /* 1k */
208
209   if( filesize < sizelimit )
210     /*
211      * Raw byte count is less than 1 kB; we may simply emit it.
212      */
213     retval = sprintf( buf, "%lu B", filesize );
214
215   else
216   {
217     /* The raw byte count is too large to be readily assimilated; we
218      * scale it down to an appropriate value, and append the appropriate
219      * scaling indicator.
220      */
221     unsigned long frac = filesize;
222     const unsigned long fracmask = sizelimit - 1;
223     const char *scale_indicator = "kMGT";
224
225     /* A ten bit right shift scales by a factor of 1k; continue shifting
226      * until the ultimate value is less than 1k...
227      */
228     while( (filesize >>= 10) >= sizelimit )
229     {
230       /* ...noting the residual at each shift, and adjusting the scaling
231        * indicator selection to suit.
232        */
233       frac = filesize;
234       ++scale_indicator;
235     }
236     /* Finally, emit the scaled result to the nearest one hundredth part
237      * of the ultimate scaling unit.
238      */
239     retval = sprintf
240       ( buf, "%lu.%02lu %cB",
241         filesize, percentage( frac & fracmask, sizelimit ), *scale_indicator
242       );
243   }
244   return retval;
245 }
246
247 /* To facilitate the implementation of the pkgInternetAgent class, which
248  * is declared below:
249  */
250 #if IMPLEMENTATION_LEVEL == SETUP_TOOL_COMPONENT
251
252 /* Within the setup tool, the pkgInternetAgent::SetRetryOptions() method
253  * requires a pointer to a pkgSetupAction...
254  */
255  typedef pkgSetupAction *INTERNET_RETRY_REQUESTER;
256
257 #else
258 /* ...whereas, in the general case, it requires a pointer to a pkgXmlNode.
259  */
260  typedef pkgXmlNode *INTERNET_RETRY_REQUESTER;
261
262 #endif
263
264 class pkgInternetAgent
265 {
266   /* A minimal, locally implemented class, instantiated ONCE as a
267    * global object, to ensure that wininet's global initialisation is
268    * completed at the proper time, without us doing it explicitly.
269    */
270   private:
271     HINTERNET SessionHandle;
272     int connection_delay, delay_factor, retries, retry_interval;
273
274   public:
275     inline pkgInternetAgent():SessionHandle( NULL )
276     {
277       /* Constructor...
278        *
279        * This is called during DLL initialisation; thus it seems to be
280        * the ideal place to perform one time internet connection setup.
281        * However, Microsoft caution against doing much here, (especially
282        * creation of threads, either directly or indirectly); thus we
283        * defer the connection setup until we ultimately need it.
284        */
285     }
286     inline ~pkgInternetAgent()
287     {
288       /* Destructor...
289        */
290       if( SessionHandle != NULL )
291         Close( SessionHandle );
292     }
293     void SetRetryOptions( INTERNET_RETRY_REQUESTER, const char* );
294     HINTERNET OpenURL( const char* );
295
296     /* Remaining methods are simple inline wrappers for the
297      * wininet functions we plan to use...
298      */
299     inline unsigned long QueryStatus( HINTERNET id )
300     {
301       unsigned long ok, idx = 0, len = sizeof( ok );
302       if( HttpQueryInfo( id, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE,
303             &ok, &len, &idx )
304         ) return ok;
305       return 0;
306     }
307     inline unsigned long QueryContentLength( HINTERNET id )
308     {
309       unsigned long content_len, idx = 0, len = sizeof( content_len );
310       if( HttpQueryInfo( id, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_CONTENT_LENGTH,
311             &content_len, &len, &idx )
312         ) return content_len;
313       return 0;
314     }
315     inline int Read( HINTERNET dl, char *buf, size_t max, unsigned long *count )
316     {
317       return InternetReadFile( dl, buf, max, count );
318     }
319     inline int Close( HINTERNET id )
320     {
321       return InternetCloseHandle( id );
322     }
323 };
324
325 /* This is the one and only instantiation of an object of this class.
326  */
327 static pkgInternetAgent pkgDownloadAgent;
328
329 class pkgInternetStreamingAgent
330 {
331   /* Another locally implemented class; each individual file download
332    * gets its own instance of this, either as-is for basic data transfer,
333    * or as a specialised derivative of this base class.
334    */
335   protected:
336     const char *filename;
337     const char *dest_template;
338
339     char *dest_file;
340     HINTERNET dl_host;
341     pkgDownloadMeter *dl_meter;
342     int dl_status;
343
344   private:
345     virtual int TransferData( int );
346
347   public:
348     pkgInternetStreamingAgent( const char*, const char* );
349     virtual ~pkgInternetStreamingAgent();
350
351     virtual int Get( const char* );
352     inline const char *DestFile(){ return dest_file; }
353 };
354
355 pkgInternetStreamingAgent::pkgInternetStreamingAgent
356 ( const char *local_name, const char *dest_specification )
357 {
358   /* Constructor for the pkgInternetStreamingAgent class.
359    */
360   filename = local_name;
361   dest_template = dest_specification;
362   dest_file = (char *)(malloc( mkpath( NULL, dest_template, filename, NULL ) ));
363   if( dest_file != NULL )
364     mkpath( dest_file, dest_template, filename, NULL );
365 }
366
367 pkgInternetStreamingAgent::~pkgInternetStreamingAgent()
368 {
369   /* Destructor needs to free the heap memory allocated by the
370    * constructor, for storage of "dest_file" name.
371    */
372   free( (void *)(dest_file) );
373 }
374
375 void pkgInternetAgent::SetRetryOptions
376 ( INTERNET_RETRY_REQUESTER referrer, const char *url_template )
377 {
378   /* Initialisation method, invoked immediately prior to the start
379    * of each archive download request, to establish the options for
380    * retrying any failed host connection request.
381    *
382    * The first of any sequence of connection attempts may always be
383    * initiated immediately.
384    */
385   connection_delay = 0;
386
387   /* If any further attempts are necessary, we will delay them
388    * at progressively increasing intervals, to give us the best
389    * possible chance to circumvent throttling of excess frequency
390    * connection requests, by the download server.
391    *
392    * FIXME: for each change of host domain, we should establish
393    * settings by consulting the configuration profile; for the
394    * time being, we simply assign fixed defaults.
395    */
396   delay_factor = INTERNET_DELAY_FACTOR;
397   retry_interval = INTERNET_RETRY_INTERVAL;
398   retries = INTERNET_RETRY_ATTEMPTS;
399 }
400
401 HINTERNET pkgInternetAgent::OpenURL( const char *URL )
402 {
403   /* Open an internet data stream.
404    */
405   HINTERNET ResourceHandle;
406
407   /* This requires an internet
408    * connection to have been established...
409    */
410   if(  (SessionHandle == NULL)
411   &&   (InternetAttemptConnect( 0 ) == ERROR_SUCCESS)  )
412     /*
413      * ...so, on first call, we perform the connection setup
414      * which we deferred from the class constructor; (MSDN
415      * cautions that this MUST NOT be done in the constructor
416      * for any global class object such as ours).
417      */
418     SessionHandle = InternetOpen
419       ( "MinGW Installer", INTERNET_OPEN_TYPE_PRECONFIG,
420          NULL, NULL, 0
421       );
422   
423   /* Aggressively attempt to acquire a resource handle, which we may use
424    * to access the specified URL; (schedule a maximum of five attempts).
425    */
426   do { pkgDownloadMeter::SpinWait( 1, URL );
427
428        /* Distribute retries at geometrically incrementing intervals.
429         */
430        if( connection_delay > 0 )
431          /* This is not the first time we've tried to open this URL;
432           * compute the appropriate retry interval, and wait between
433           * successive attempts to establish the connection.
434           */
435          Sleep( connection_delay = delay_factor * connection_delay );
436        else
437          /* This is the first attempt to open this URL; don't wait,
438           * but set up the baseline, in milliseconds, for interval
439           * computation, in the event that further attempts may be
440           * required.
441           */
442          connection_delay = retry_interval;
443
444        ResourceHandle = InternetOpenUrl
445          (
446            /* Here, we attempt to assign a URL specific resource handle,
447             * within the scope of the SessionHandle obtained above, to
448             * manage the connection for the requested URL.
449             *
450             * Note: Scott Michel suggests INTERNET_FLAG_EXISTING_CONNECT
451             * here; MSDN tells us it is useful only for FTP connections.
452             * Since we are primarily interested in HTTP connections, it
453             * may not help us.  However, it does no harm, and MSDN isn't
454             * always the reliable source of information we might like.
455             * Persistent HTTP connections aren't entirely unknown, (and
456             * indeed, MSDN itself tells us we need to use one, when we
457             * negotiate proxy authentication); thus, we may just as well
458             * specify it anyway, on the off-chance that it may introduce
459             * an undocumented benefit beyond wishful thinking.
460             */
461            SessionHandle, URL, NULL, 0, INTERNET_FLAG_EXISTING_CONNECT, 0
462          );
463        if( ResourceHandle == NULL )
464        {
465          /* We failed to acquire a handle for the URL resource; we may retry
466           * unless we have exhausted the specified retry limit...
467           */
468          if( --retries < 1 )
469          {
470            /* ...in which case, we diagnose failure to open the URL.
471             */
472            DEBUG_INVOKE_IF( DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ),
473              dmh_printf( "%s\nConnection failed(status=%u); abandoned.\n",
474                  URL, GetLastError() )
475              );
476            dmh_notify( DMH_ERROR, "%s:cannot open URL\n", URL );
477          }
478          else DEBUG_INVOKE_IF( DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ),
479            dmh_printf( "%s\nConnecting ... failed(status=%u); retrying in %ds...\n",
480                URL, GetLastError(), delay_factor * connection_delay / 1000 )
481            );
482        }
483        else
484        { /* We got a handle for the URL resource, but we cannot yet be sure
485           * that it is ready for use; we may still need to address a need for
486           * proxy or server authentication, or other temporary fault.
487           */
488          int retry = 5;
489          unsigned long ResourceStatus, ResourceErrno;
490          do { /* We must capture any error code which may have been returned,
491                * BEFORE we move on to evaluate the resource status, (since the
492                * procedure for checking status may change the error code).
493                */
494               ResourceErrno = GetLastError();
495               ResourceStatus = QueryStatus( ResourceHandle );
496               if( ResourceStatus == HTTP_STATUS_PROXY_AUTH_REQ )
497               {
498                 /* We've identified a requirement for proxy authentication;
499                  * here we simply hand the task off to the Microsoft handler,
500                  * to solicit the appropriate response from the user.
501                  *
502                  * FIXME: this may be a reasonable approach when running in
503                  * a GUI context, but is rather inelegant in the CLI context.
504                  * Furthermore, this particular implementation provides only
505                  * for proxy authentication, ignoring the possibility that
506                  * server authentication may be required.  We may wish to
507                  * revisit this later.
508                  */
509                 unsigned long user_response;
510                 do { user_response = InternetErrorDlg
511                        ( dmh_dialogue_context(), ResourceHandle, ResourceErrno,
512                          FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
513                          FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
514                          FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
515                          NULL
516                        );
517                      /* Having obtained authentication credentials from
518                       * the user, we may retry the open URL request...
519                       */
520                      if(  (user_response == ERROR_INTERNET_FORCE_RETRY)
521                      &&  HttpSendRequest( ResourceHandle, NULL, 0, 0, 0 )  )
522                      {
523                        /* ...and, if successful...
524                         */
525                        ResourceErrno = GetLastError();
526                        ResourceStatus = QueryStatus( ResourceHandle );
527                        if( ResourceStatus == HTTP_STATUS_OK )
528                          /*
529                           * ...ensure that the response is anything but 'retry',
530                           * so that we will break out of the retry loop...
531                           */
532                          user_response ^= -1L;
533                      }
534                      /* ...otherwise, we keep retrying when appropriate.
535                       */
536                    } while( user_response == ERROR_INTERNET_FORCE_RETRY );
537               }
538               else if( ResourceStatus != HTTP_STATUS_OK )
539               {
540                 /* Other failure modes may not be so readily recoverable;
541                  * with little hope of success, retry anyway.
542                  */
543                 DEBUG_INVOKE_IF( DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ),
544                     dmh_printf( "%s: abnormal request status = %u; retrying...\n",
545                         URL, ResourceStatus
546                   ));
547                 if( HttpSendRequest( ResourceHandle, NULL, 0, 0, 0 ) )
548                   ResourceStatus = QueryStatus( ResourceHandle );
549               }
550             } while( (ResourceStatus != HTTP_STATUS_OK) && (retry-- > 0) );
551
552          /* Confirm that the URL was (eventually) opened successfully...
553           */
554          if( ResourceStatus == HTTP_STATUS_OK )
555            /*
556             * ...in which case, we have no need to schedule any further
557             * retries.
558             */
559            retries = 0;
560
561          else
562          { /* The resource handle we've acquired isn't useable; discard it,
563             * so we can reclaim any resources associated with it.
564             */
565            Close( ResourceHandle );
566
567            /* When we have exhausted our retry limit...
568             */
569            if( --retries < 1 )
570            {
571              /* Give up; nullify our resource handle to indicate failure.
572               */
573              ResourceHandle = NULL;
574
575              /* Issue a diagnostic advising the user to refer the problem
576               * to the mingw-get maintainer for possible follow-up; (note
577               * that we want to group the following messages into a single
578               * message "digest", but if the caller is already doing so,
579               * then we simply incorporate these, and delegate flushing
580               * of the completed "digest" to the caller).
581               */
582              uint16_t dmh_cached = dmh_control( DMH_GET_CONTROL_STATE );
583              dmh_cached &= dmh_control( DMH_BEGIN_DIGEST );
584              dmh_notify( DMH_WARNING,
585                  "%s: opened with unexpected status: code = %u\n",
586                  URL, ResourceStatus
587                );
588              dmh_notify( DMH_WARNING,
589                  "please report this to the mingw-get maintainer\n"
590                );
591              if( dmh_cached == 0 ) dmh_control( DMH_END_DIGEST );
592            }
593          }
594        }
595        /* If we haven't yet acquired a valid resource handle, and we haven't
596         * yet exhausted our retry limit, go back and try again.
597         */
598      } while( retries > 0 );
599     pkgDownloadMeter::SpinWait( 0 );
600
601   /* Ultimately, we return the resource handle for the opened URL,
602    * or NULL if the open request failed.
603    */
604   return ResourceHandle;
605 }
606
607 int pkgInternetStreamingAgent::TransferData( int fd )
608 {
609   /* In the case of this base class implementation,
610    * we simply read the file's data from the Internet source,
611    * and write a verbatim copy to the destination file.
612    */
613   char buf[8192]; unsigned long count, tally = 0;
614   do { dl_status = pkgDownloadAgent.Read( dl_host, buf, sizeof( buf ), &count );
615        dl_meter->Update( tally += count );
616        write( fd, buf, count );
617      } while( dl_status && (count > 0) );
618
619   DEBUG_INVOKE_IF(
620       DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ) && (dl_status == 0),
621       dmh_printf( "\nInternetReadFile:download error:%d\n", GetLastError() )
622     );
623   return dl_status;
624 }
625
626 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
627
628 static const char *get_host_info
629 ( pkgXmlNode *ref, const char *property, const char *fallback = NULL )
630 {
631   /* Helper function to retrieve host information from the XML catalogue.
632    *
633    * Call with property = "url", to retrieve the URL template to pass as
634    * "fmt" argument to mkpath(), or with property = "mirror", to retrieve
635    * the substitution text for the "modifier" argument.
636    */
637   const char *uri = NULL;
638   while( ref != NULL )
639   {
640     /* Starting from the "ref" package entry in the catalogue...
641      */
642     pkgXmlNode *host = ref->FindFirstAssociate( download_host_key );
643     while( host != NULL )
644     {
645       /* Examine its associate tags; if we find one of type
646        * "download-host", with the requisite property, then we
647        * immediately return that property value...
648        */
649       if( (uri = host->GetPropVal( property, NULL )) != NULL )
650         return uri;
651
652       /* Otherwise, we look for any other candidate tags
653        * associated with the same catalogue entry...
654        */
655       host = host->FindNextAssociate( download_host_key );
656     }
657     /* Failing an immediate match, extend the search to the
658      * ancestors of the initial reference entry...
659      */
660     ref = ref->GetParent();
661   }
662   /* ...and ultimately, if no match is found, we return the
663    * specified "fallback" property value.
664    */
665   return fallback;
666 }
667
668 #elif IMPLEMENTATION_LEVEL == SETUP_TOOL_COMPONENT
669
670 static const char *get_host_info
671 ( void *ref, const char *property, const char *fallback = NULL )
672 {
673   /* Customised helper to load the download host URI template
674    * directly from the setup tool's resource data section.
675    */
676   static const char *uri_template = NULL;
677   if( uri_template == NULL )
678     uri_template = strdup( WTK::StringResource( NULL, ID_DOWNLOAD_HOST_URI ) );
679   return (strcmp( property, uri_key ) == 0) ? uri_template : fallback;
680 }
681
682 #endif
683
684 static inline
685 int set_transit_path( const char *path, const char *file, char *buf = NULL )
686 {
687   /* Helper to define the transitional path name for downloaded files,
688    * used to save the file data while the download is in progress.
689    */
690   static const char *transit_dir = "/.in-transit";
691   return mkpath( buf, path, file, transit_dir );
692 }
693
694 int pkgInternetStreamingAgent::Get( const char *from_url )
695 {
696   /* Download a file from the specified internet URL.
697    *
698    * Before download commences, we accept that this may fail...
699    */
700   dl_status = 0;
701
702   /* Set up a "transit-file" to receive the downloaded content.
703    */
704   char transit_file[set_transit_path( dest_template, filename )];
705   int fd; set_transit_path( dest_template, filename, transit_file );
706
707 //dmh_printf( "Get: initialise transfer file %s ... ", transit_file );
708   chmod( transit_file, S_IWRITE ); unlink( transit_file );
709   if( (fd = set_output_stream( transit_file, 0644 )) >= 0 )
710   {
711 //dmh_printf( "success\nGet: open URL %s ... ", from_url );
712     /* The "transit-file" is ready to receive incoming data...
713      * Configure and invoke the download handler to copy the data
714      * from the appropriate host URL, to this "transit-file".
715      */
716     if( (dl_host = pkgDownloadAgent.OpenURL( from_url )) != NULL )
717     {
718 //dmh_printf( "success\n" );
719       if( pkgDownloadAgent.QueryStatus( dl_host ) == HTTP_STATUS_OK )
720       {
721         /* With the download transaction fully specified, we may
722          * request processing of the file transfer...
723          */
724         if( (dl_meter = pkgDownloadMeter::UseGUI()) != NULL )
725         {
726           /* ...with progress monitoring delegated to the GUI's
727            * dialogue box, when running under its auspices...
728            */
729           dl_meter->ResetGUI(
730               filename, pkgDownloadAgent.QueryContentLength( dl_host )
731             );
732           dl_status = TransferData( fd );
733         }
734         else
735         { /* ...otherwise creating our own TTY progress monitor,
736            * when running under the auspices of the CLI.
737            */
738           pkgDownloadMeterTTY download_meter(
739               from_url, pkgDownloadAgent.QueryContentLength( dl_host )
740             );
741           dl_meter = &download_meter;
742
743           /* Note that the following call MUST be kept within the
744            * scope in which the progress monitor was created; thus,
745            * it CANNOT be factored out of this "else" block scope,
746            * even though it also appears at the end of the scope
747            * of the preceding "if" block.
748            */
749           dl_status = TransferData( fd );
750         }
751       }
752       else DEBUG_INVOKE_IF( DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ),
753           dmh_printf( "OpenURL:error:%d\n", GetLastError() )
754         );
755
756       /* We are done with the URL handle; close it.
757        */
758       pkgDownloadAgent.Close( dl_host );
759     }
760 //else dmh_printf( "failed\n" );
761
762     /* Always close the "transit-file", whether the download
763      * was successful, or not...
764      */
765     close( fd );
766     if( dl_status )
767       /*
768        * When successful, we move the "transit-file" to its
769        * final downloaded location...
770        */
771       rename( transit_file, dest_file );
772     else
773       /* ...otherwise, we discard the incomplete "transit-file",
774        * leaving the caller to diagnose the failure.
775        */
776       unlink( transit_file );
777   }
778 //else dmh_printf( "failed\n" );
779
780   /* Report success or failure to the caller...
781    */
782   return dl_status;
783 }
784
785 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
786
787 void pkgActionItem::PrintURI
788 ( const char *package_name, int (*output)( const char * ) )
789 {
790   /* Public method to display the URI from which a package archive
791    * may be downloaded; called with "package_name" assigned by either
792    * ArchiveName() or SourceArchiveName() as appropriate, and...
793    */
794   if( ! match_if_explicit( package_name, value_none ) )
795   {
796     /* ...applicable only to real (i.e. not meta) packages.
797      *
798      * We begin by retrieving the URI template associated with
799      * the specified package...
800      */
801     const char *url_template = get_host_info( Selection(), uri_key );
802     if( url_template != NULL )
803     {
804       /* ...then filling in the package name and preferred mirror
805        * assignment, as if preparing to initiate a download...
806        */
807       const char *mirror = get_host_info( Selection(), mirror_key );
808       char package_url[mkpath( NULL, url_template, package_name, mirror )];
809       mkpath( package_url, url_template, package_name, mirror );
810
811       /* ...then, rather than actually initiate the download,
812        * we simply write out the generated URI to stdout.
813        */
814       output( package_url );
815     }
816   }
817 }
818
819 #endif /* PACKAGE_BASE_COMPONENT */
820
821 void pkgActionItem::DownloadSingleArchive
822 ( const char *package_name, const char *archive_cache_path )
823 {
824   pkgInternetStreamingAgent download( package_name, archive_cache_path );
825
826   /* Check if the required archive is already available locally...
827    */
828   if(  ((flags & ACTION_DOWNLOAD) == ACTION_DOWNLOAD)
829   &&   ((access( download.DestFile(), R_OK ) != 0) && (errno == ENOENT))  )
830   {
831     /* ...if not, ask the download agent to fetch it,
832      * anticipating that this may fail...
833      */
834     flags |= ACTION_DOWNLOAD_FAILED;
835     const char *url_template = get_host_info( Selection(), uri_key );
836     if( url_template != NULL )
837     {
838       /* ...from the URL constructed from the template specified in
839        * the package repository catalogue (configuration database).
840        */
841       const char *mirror = get_host_info( Selection(), mirror_key );
842       char package_url[mkpath( NULL, url_template, package_name, mirror )];
843       mkpath( package_url, url_template, package_name, mirror );
844
845       /* Enable retrying of failed connection attempts, according to the
846        * preferences, if any, which have been configured for the repository
847        * associated with the current URL template, or with default settings
848        * otherwise, then initiate the package download process.
849        */
850       pkgDownloadAgent.SetRetryOptions( Selection(), url_template );
851       if( download.Get( package_url ) > 0 )
852         /*
853          * Download was successful; clear the pending and failure flags.
854          */
855         flags &= ~(ACTION_DOWNLOAD | ACTION_DOWNLOAD_FAILED);
856       else
857         /* Diagnose failure; leave pending flag set.
858          */
859         dmh_notify( DMH_ERROR,
860             "Get package: %s: download failed\n", package_url
861           );
862     }
863     else
864       /* Cannot download; the repository catalogue didn't specify a
865        * template, from which to construct a download URL...
866        */
867       dmh_notify( DMH_ERROR,
868           "Get package: %s: no URL specified for download\n", package_name
869         );
870   }
871   else
872     /* There was no need to download any file to satisfy this request.
873      */
874     flags &= ~(ACTION_DOWNLOAD);
875 }
876
877 void pkgActionItem::DownloadArchiveFiles( pkgActionItem *current )
878 {
879   /* Update the local package cache, to ensure that all packages needed
880    * to complete the current set of scheduled actions are present; if any
881    * are missing, invoke an Internet download agent to fetch them.  This
882    * requires us to walk the action list...
883    */
884   while( current != NULL )
885   {
886     /* ...while we haven't run off the end, and collecting any diagnositic
887      * messages relating to any one package into a common digest...
888      */
889     dmh_control( DMH_BEGIN_DIGEST );
890     if( (current->flags & ACTION_INSTALL) == ACTION_INSTALL )
891     {
892       /* For all packages specified in the current action list,
893        * for which an "install" action is scheduled, and for which
894        * no associated archive file is present in the local archive
895        * cache, place an Internet download agent on standby to fetch
896        * the required archive from a suitable internet mirror host.
897        */
898       const char *package_name = current->Selection()->ArchiveName();
899
900       /* An explicit package name of "none" is a special case;
901        * it identifies a "virtual" meta-package...
902        */
903       if( match_if_explicit( package_name, value_none ) )
904         /*
905          * ...which requires nothing to be downloaded...
906          */
907         current->flags &= ~(ACTION_DOWNLOAD);
908
909       else
910         /* ...but we expect any other package to provide real content,
911          * for which we may need to download the package archive...
912          */
913         current->DownloadSingleArchive( package_name, pkgArchivePath() );
914     }
915     else
916       /* The current action has no associated "install" requirement,
917        * so neither is there any need to request a "download".
918        */
919       current->flags &= ~(ACTION_DOWNLOAD);
920
921     /* Flush out any diagnostics relating to the current package, then
922      * repeat the download action, for any additional packages specified
923      * in the current "actions" list.
924      */
925     dmh_control( DMH_END_DIGEST );
926     current = current->next;
927   }
928 }
929
930 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
931
932 #define DATA_CACHE_PATH         "%R" "var/cache/mingw-get/data"
933 #define WORKING_DATA_PATH       "%R" "var/lib/mingw-get/data"
934
935 /* Internet servers host package catalogues in lzma compressed format;
936  * we will decompress them "on the fly", as we download them.  To achieve
937  * this, we will use a variant of the pkgInternetStreamingAgent, using a
938  * specialised TransferData method; additionally, this will incorporate
939  * a special derivative of a pkgLzmaArchiveStream, with its GetRawData
940  * method adapted to stream data from an internet URI, instead of
941  * reading from a local file.
942  *
943  * To derive the pkgInternetLzmaStreamingAgent, we need to include the
944  * specialised declarations of a pkgArchiveStream, in order to make the
945  * declaration of pkgLzmaArchiveStream available as our base class.
946  */
947 #define  PKGSTRM_H_SPECIAL  1
948 #include "pkgstrm.h"
949
950 class pkgInternetLzmaStreamingAgent:
951 public pkgInternetStreamingAgent, public pkgLzmaArchiveStream
952 {
953   /* Specialisation of the pkgInternetStreamingAgent base class,
954    * providing decompressed copies of LZMA encoded files downloaded
955    * from the Internet; (the LZMA decompression capability is derived
956    * from the pkgLzmaArchiveStream base class).
957    */
958   public:
959     /* We need a specialised constructor...
960      */
961     pkgInternetLzmaStreamingAgent( const char*, const char* );
962
963   private:
964     /* Specialisation requires overrides for each of this pair of
965      * methods, (the first from the pkgLzmaArchiveStream base class;
966      * the second from pkgInternetStreamingAgent).
967      */
968     virtual int GetRawData( int, uint8_t*, size_t );
969     virtual int TransferData( int );
970 };
971
972 /* This specialisation of the pkgInternetStreamingAgent class needs its
973  * own constructor, simply to invoke the constructors for the base classes,
974  * (since neither is instantiated by a default constructor).
975  */
976 pkgInternetLzmaStreamingAgent::pkgInternetLzmaStreamingAgent
977 ( const char *local_name, const char *dest_specification ):
978 pkgInternetStreamingAgent( local_name, dest_specification ),
979 /*
980  * Note that, when we come to initialise the lzma streaming component
981  * of this derived class, we will be streaming directly from the internet,
982  * rather than from a file stream, so we don't require a file descriptor
983  * for the input stream; however, the class semantics still expect one.
984  * To avoid accidental association with an existing file stream, we
985  * use a negative value, (which is never a valid file descriptor);
986  * however, we must not choose -1, since the class implementation
987  * will decline to process the stream; hence, we choose -2.
988  */
989 pkgLzmaArchiveStream( -2 ){}
990
991 int pkgInternetLzmaStreamingAgent::GetRawData( int fd, uint8_t *buf, size_t max )
992 {
993   /* Fetch raw (compressed) data from the Internet host, and load it into
994    * the decompression filter's input buffer, whence the TransferData routine
995    * may retrieve it, via the filter, as an uncompressed stream.
996    */
997   unsigned long count;
998   dl_status = pkgDownloadAgent.Read( dl_host, (char *)(buf), max, &count );
999   return (int)(count);
1000 }
1001
1002 int pkgInternetLzmaStreamingAgent::TransferData( int fd )
1003 {
1004   /* In this case, we read the file's data from the Internet source,
1005    * stream it through the lzma decompression filter, and write a copy
1006    * of the resultant decompressed data to the destination file.
1007    */
1008   char buf[8192]; unsigned long count;
1009   do { count = pkgLzmaArchiveStream::Read( buf, sizeof( buf ) );
1010        write( fd, buf, count );
1011      } while( dl_status && (count > 0) );
1012
1013   DEBUG_INVOKE_IF(
1014       DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ) && (dl_status == 0),
1015       dmh_printf( "\nInternetReadFile:download error:%d\n", GetLastError() )
1016     );
1017   return dl_status;
1018 }
1019
1020 EXTERN_C const char *serial_number( const char *catalogue )
1021 {
1022   /* Local helper function to retrieve issue numbers from any repository
1023    * package catalogue; returns the result as a duplicate of the internal
1024    * string, allocated on the heap (courtesy of the strdup() function).
1025    */
1026   const char *issue;
1027   pkgXmlDocument src( catalogue );
1028
1029   if(   src.IsOk()
1030   &&  ((issue = src.GetRoot()->GetPropVal( issue_key, NULL )) != NULL)  )
1031     /*
1032      * Found an issue number; return a copy...
1033      */
1034     return strdup( issue );
1035
1036   /* If we get to here, we couldn't get a valid issue number;
1037    * whatever the reason, return NULL to indicate failure.
1038    */
1039   return NULL;
1040 }
1041
1042 void pkgXmlDocument::SyncRepository( const char *name, pkgXmlNode *repository )
1043 {
1044   /* Fetch a named package catalogue from a specified Internet repository.
1045    *
1046    * Package catalogues are XML files; the master copy on the Internet host
1047    * must be stored in lzma compressed format, and named to comply with the
1048    * convention "%F.xml.lzma", in which "%F" represents the value of the
1049    * "name" argument passed to this pkgXmlDocument class method.
1050    */ 
1051   const char *url_template;
1052   if( (url_template = repository->GetPropVal( uri_key, NULL )) != NULL )
1053   {
1054     /* Initialise a streaming agent, to manage the catalogue download;
1055      * (note that we must include the "%/M" placeholder in the template
1056      * for the local name, to accommodate the name of the intermediate
1057      * "in-transit" directory used by the streaming agent).
1058      */
1059     pkgInternetLzmaStreamingAgent download( name, DATA_CACHE_PATH "%/M/%F.xml" );
1060     {
1061       /* Construct the full URI for the master catalogue, and stream it to
1062        * a locally cached, decompressed copy of the XML file.
1063        */
1064       const char *mirror = repository->GetPropVal( mirror_key, NULL );
1065       char catalogue_url[mkpath( NULL, url_template, name, mirror )];
1066       mkpath( catalogue_url, url_template, name, mirror );
1067
1068       /* Enable retries according to the preferences, if any, as
1069        * configured for the repository, or adopt default settings
1070        * otherwise, then initiate the download process for the
1071        * catalogue file.
1072        */
1073       pkgDownloadAgent.SetRetryOptions( repository, url_template );
1074       if( download.Get( catalogue_url ) <= 0 )
1075         dmh_notify( DMH_ERROR,
1076             "Sync Repository: %s: download failed\n", catalogue_url
1077           );
1078     }
1079
1080     /* We will only replace our current working copy of this catalogue,
1081      * (if one already exists), with the copy we just downloaded, if this
1082      * downloaded copy bears an issue number indicating that it is more
1083      * recent than the working copy.
1084      */
1085     const char *repository_version, *working_version;
1086     if( (repository_version = serial_number( download.DestFile() )) != NULL )
1087     {
1088       /* Identify the location for the working copy, (if it exists).
1089        */
1090       const char *working_copy_path_name = WORKING_DATA_PATH "/%F.xml";
1091       char working_copy[mkpath( NULL, working_copy_path_name, name, NULL )];
1092       mkpath( working_copy, working_copy_path_name, name, NULL );
1093
1094       /* Compare issue serial numbers...
1095        */
1096       if( ((working_version = serial_number( working_copy )) == NULL)
1097       ||  ((strcmp( repository_version, working_version )) > 0)        )
1098       {
1099         /* In these circumstances, we couldn't identify an issue number
1100          * for the working copy of the catalogue; (maybe there is no such
1101          * catalogue, or maybe it doesn't specify a valid issue number);
1102          * in either case, we promote the downloaded copy in its place.
1103          *
1104          * FIXME: we assume that the working file and the downloaded copy
1105          * are stored on the same physical file system device, so we may
1106          * replace the former by simply deleting it, and renaming the
1107          * latter with its original path name; we make no provision for
1108          * replacing the working version by physical data copying.
1109          */
1110         unlink( working_copy );
1111         rename( download.DestFile(), working_copy );
1112       }
1113
1114       /* The issue numbers, returned by the serial_number() function, were
1115        * allocated on the heap; free them to avoid leaking memory!
1116        */
1117       free( (void *)(repository_version) );
1118       /*
1119        * The working copy issue number may be represented by a NULL pointer;
1120        * while it may be safe to call free on this, it just *seems* wrong, so
1121        * we check it first, to be certain.
1122        */
1123       if( working_version != NULL )
1124         free( (void *)(working_version) );
1125     }
1126
1127     /* If the downloaded copy of the catalogue is still in the download cache,
1128      * we have chosen to keep a previous working copy, so we have no further
1129      * use for the downloaded copy; discard it, noting that we don't need to
1130      * confirm its existence because this will fail silently, if it is no
1131      * longer present.
1132      */
1133     unlink( download.DestFile() );
1134   }
1135 }
1136
1137 #endif /* PACKAGE_BASE_COMPONENT */
1138
1139 /* $RCSfile$: end of file */