6 * Written by Keith Marshall <keithmarshall@users.sourceforge.net>
7 * Copyright (C) 2009-2013, MinGW.org Project
10 * Implementation of the package download machinery for mingw-get.
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.
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.
27 #define USES_SAFE_STRCMP 1
28 #define WIN32_LEAN_AND_MEAN
30 #define _WIN32_WINNT 0x0500 /* for GetConsoleWindow() kludge */
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).
41 #define dmh_dialogue_context() GetConsoleWindow()
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.
69 pkgDownloadMeter *pkgDownloadMeter::primary = NULL;
71 inline void pkgDownloadMeter::SpinWait( int mode, const char *uri )
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).
78 if( primary != NULL ) primary->SpinWaitAction( mode, uri );
81 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
83 /* Implementation of a download meter class, displaying download
84 * statistics within a CLI application context.
86 class pkgDownloadMeterTTY: public pkgDownloadMeter
89 pkgDownloadMeterTTY( const char*, unsigned long );
90 virtual ~pkgDownloadMeterTTY();
92 virtual int Update( unsigned long );
95 /* This buffer is used to store each compiled status report,
96 * in preparation for display on the console.
98 const char *source_url;
99 char status_report[80];
104 pkgDownloadMeterTTY::pkgDownloadMeterTTY( const char *url, unsigned long length ):
105 source_url( url ){ content_length = length; }
107 /* ...and destructor.
109 pkgDownloadMeterTTY::~pkgDownloadMeterTTY()
111 if( source_url == NULL )
115 #elif IMPLEMENTATION_LEVEL == SETUP_TOOL_COMPONENT
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.
122 class pkgDownloadMeterTTY: public pkgDownloadMeter
124 /* Implementation of a dummy download meter class, sufficient
125 * to promote an illusion of TTY metering capability.
128 pkgDownloadMeterTTY( const char*, unsigned long ){}
129 virtual int Update( unsigned long ){ return 0; }
134 static inline __attribute__((__always_inline__))
135 unsigned long pow10mul( register unsigned long x, unsigned power )
137 /* Inline helper to perform a fast integer multiplication of "x"
138 * by a specified power of ten.
142 /* Each cycle multiplies by ten, first shifting to get "x * 2"...
146 * ...then further shifting that intermediate result, and adding,
147 * to achieve the effect of "x * 2 + x * 2 * 4".
154 static inline __attribute__((__always_inline__))
155 unsigned long percentage( unsigned long x, unsigned long q )
157 /* Inline helper to compute "x" as an integer percentage of "q".
159 return pow10mul( x, 2 ) / q;
162 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
164 int pkgDownloadMeterTTY::Update( unsigned long count )
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.
172 char *p = status_report;
173 int barlen = (content_length > count)
174 ? (((count << 1) + count) << 4) / content_length
175 : (content_length > 0) ? 48 : 0;
177 /* We may safely use sprintf() to assemble the status report, because
178 * we control the field lengths to always fit within the buffer.
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, "| ???" );
191 if( source_url != NULL )
193 dmh_printf( "%s\n", source_url );
196 return dmh_printf( "\r%s%%", status_report );
201 int pkgDownloadMeter::SizeFormat( char *buf, unsigned long filesize )
203 /* Helper method to format raw byte counts as B, kB, MB, GB, TB, as
204 * appropriate; (this NEVER requires more than ten characters).
207 const unsigned long sizelimit = 1 << 10; /* 1k */
209 if( filesize < sizelimit )
211 * Raw byte count is less than 1 kB; we may simply emit it.
213 retval = sprintf( buf, "%lu B", filesize );
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
221 unsigned long frac = filesize;
222 const unsigned long fracmask = sizelimit - 1;
223 const char *scale_indicator = "kMGT";
225 /* A ten bit right shift scales by a factor of 1k; continue shifting
226 * until the ultimate value is less than 1k...
228 while( (filesize >>= 10) >= sizelimit )
230 /* ...noting the residual at each shift, and adjusting the scaling
231 * indicator selection to suit.
236 /* Finally, emit the scaled result to the nearest one hundredth part
237 * of the ultimate scaling unit.
240 ( buf, "%lu.%02lu %cB",
241 filesize, percentage( frac & fracmask, sizelimit ), *scale_indicator
247 /* To facilitate the implementation of the pkgInternetAgent class, which
250 #if IMPLEMENTATION_LEVEL == SETUP_TOOL_COMPONENT
252 /* Within the setup tool, the pkgInternetAgent::SetRetryOptions() method
253 * requires a pointer to a pkgSetupAction...
255 typedef pkgSetupAction *INTERNET_RETRY_REQUESTER;
258 /* ...whereas, in the general case, it requires a pointer to a pkgXmlNode.
260 typedef pkgXmlNode *INTERNET_RETRY_REQUESTER;
264 class pkgInternetAgent
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.
271 HINTERNET SessionHandle;
272 int connection_delay, delay_factor, retries, retry_interval;
275 inline pkgInternetAgent():SessionHandle( NULL )
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.
286 inline ~pkgInternetAgent()
290 if( SessionHandle != NULL )
291 Close( SessionHandle );
293 void SetRetryOptions( INTERNET_RETRY_REQUESTER, const char* );
294 HINTERNET OpenURL( const char* );
296 /* Remaining methods are simple inline wrappers for the
297 * wininet functions we plan to use...
299 inline unsigned long QueryStatus( HINTERNET id )
301 unsigned long ok, idx = 0, len = sizeof( ok );
302 if( HttpQueryInfo( id, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE,
307 inline unsigned long QueryContentLength( HINTERNET id )
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;
315 inline int Read( HINTERNET dl, char *buf, size_t max, unsigned long *count )
317 return InternetReadFile( dl, buf, max, count );
319 inline int Close( HINTERNET id )
321 return InternetCloseHandle( id );
325 /* This is the one and only instantiation of an object of this class.
327 static pkgInternetAgent pkgDownloadAgent;
329 class pkgInternetStreamingAgent
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.
336 const char *filename;
337 const char *dest_template;
341 pkgDownloadMeter *dl_meter;
345 virtual int TransferData( int );
348 pkgInternetStreamingAgent( const char*, const char* );
349 virtual ~pkgInternetStreamingAgent();
351 virtual int Get( const char* );
352 inline const char *DestFile(){ return dest_file; }
355 pkgInternetStreamingAgent::pkgInternetStreamingAgent
356 ( const char *local_name, const char *dest_specification )
358 /* Constructor for the pkgInternetStreamingAgent class.
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 );
367 pkgInternetStreamingAgent::~pkgInternetStreamingAgent()
369 /* Destructor needs to free the heap memory allocated by the
370 * constructor, for storage of "dest_file" name.
372 free( (void *)(dest_file) );
375 void pkgInternetAgent::SetRetryOptions
376 ( INTERNET_RETRY_REQUESTER referrer, const char *url_template )
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.
382 * The first of any sequence of connection attempts may always be
383 * initiated immediately.
385 connection_delay = 0;
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.
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.
396 delay_factor = INTERNET_DELAY_FACTOR;
397 retry_interval = INTERNET_RETRY_INTERVAL;
398 retries = INTERNET_RETRY_ATTEMPTS;
401 HINTERNET pkgInternetAgent::OpenURL( const char *URL )
403 /* Open an internet data stream.
405 HINTERNET ResourceHandle;
407 /* This requires an internet
408 * connection to have been established...
410 if( (SessionHandle == NULL)
411 && (InternetAttemptConnect( 0 ) == ERROR_SUCCESS) )
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).
418 SessionHandle = InternetOpen
419 ( "MinGW Installer", INTERNET_OPEN_TYPE_PRECONFIG,
423 /* Aggressively attempt to acquire a resource handle, which we may use
424 * to access the specified URL; (schedule a maximum of five attempts).
426 do { pkgDownloadMeter::SpinWait( 1, URL );
428 /* Distribute retries at geometrically incrementing intervals.
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.
435 Sleep( connection_delay = delay_factor * connection_delay );
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
442 connection_delay = retry_interval;
444 ResourceHandle = InternetOpenUrl
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.
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.
461 SessionHandle, URL, NULL, 0, INTERNET_FLAG_EXISTING_CONNECT, 0
463 if( ResourceHandle == NULL )
465 /* We failed to acquire a handle for the URL resource; we may retry
466 * unless we have exhausted the specified retry limit...
470 /* ...in which case, we diagnose failure to open the URL.
472 DEBUG_INVOKE_IF( DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ),
473 dmh_printf( "%s\nConnection failed(status=%u); abandoned.\n",
474 URL, GetLastError() )
476 dmh_notify( DMH_ERROR, "%s:cannot open URL\n", URL );
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 )
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.
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).
494 ResourceErrno = GetLastError();
495 ResourceStatus = QueryStatus( ResourceHandle );
496 if( ResourceStatus == HTTP_STATUS_PROXY_AUTH_REQ )
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.
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.
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,
517 /* Having obtained authentication credentials from
518 * the user, we may retry the open URL request...
520 if( (user_response == ERROR_INTERNET_FORCE_RETRY)
521 && HttpSendRequest( ResourceHandle, NULL, 0, 0, 0 ) )
523 /* ...and, if successful...
525 ResourceErrno = GetLastError();
526 ResourceStatus = QueryStatus( ResourceHandle );
527 if( ResourceStatus == HTTP_STATUS_OK )
529 * ...ensure that the response is anything but 'retry',
530 * so that we will break out of the retry loop...
532 user_response ^= -1L;
534 /* ...otherwise, we keep retrying when appropriate.
536 } while( user_response == ERROR_INTERNET_FORCE_RETRY );
538 else if( ResourceStatus != HTTP_STATUS_OK )
540 /* Other failure modes may not be so readily recoverable;
541 * with little hope of success, retry anyway.
543 DEBUG_INVOKE_IF( DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ),
544 dmh_printf( "%s: abnormal request status = %u; retrying...\n",
547 if( HttpSendRequest( ResourceHandle, NULL, 0, 0, 0 ) )
548 ResourceStatus = QueryStatus( ResourceHandle );
550 } while( (ResourceStatus != HTTP_STATUS_OK) && (retry-- > 0) );
552 /* Confirm that the URL was (eventually) opened successfully...
554 if( ResourceStatus == HTTP_STATUS_OK )
556 * ...in which case, we have no need to schedule any further
562 { /* The resource handle we've acquired isn't useable; discard it,
563 * so we can reclaim any resources associated with it.
565 Close( ResourceHandle );
567 /* When we have exhausted our retry limit...
571 /* Give up; nullify our resource handle to indicate failure.
573 ResourceHandle = NULL;
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).
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",
588 dmh_notify( DMH_WARNING,
589 "please report this to the mingw-get maintainer\n"
591 if( dmh_cached == 0 ) dmh_control( DMH_END_DIGEST );
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.
598 } while( retries > 0 );
599 pkgDownloadMeter::SpinWait( 0 );
601 /* Ultimately, we return the resource handle for the opened URL,
602 * or NULL if the open request failed.
604 return ResourceHandle;
607 int pkgInternetStreamingAgent::TransferData( int fd )
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.
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) );
620 DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ) && (dl_status == 0),
621 dmh_printf( "\nInternetReadFile:download error:%d\n", GetLastError() )
626 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
628 static const char *get_host_info
629 ( pkgXmlNode *ref, const char *property, const char *fallback = NULL )
631 /* Helper function to retrieve host information from the XML catalogue.
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.
637 const char *uri = NULL;
640 /* Starting from the "ref" package entry in the catalogue...
642 pkgXmlNode *host = ref->FindFirstAssociate( download_host_key );
643 while( host != NULL )
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...
649 if( (uri = host->GetPropVal( property, NULL )) != NULL )
652 /* Otherwise, we look for any other candidate tags
653 * associated with the same catalogue entry...
655 host = host->FindNextAssociate( download_host_key );
657 /* Failing an immediate match, extend the search to the
658 * ancestors of the initial reference entry...
660 ref = ref->GetParent();
662 /* ...and ultimately, if no match is found, we return the
663 * specified "fallback" property value.
668 #elif IMPLEMENTATION_LEVEL == SETUP_TOOL_COMPONENT
670 static const char *get_host_info
671 ( void *ref, const char *property, const char *fallback = NULL )
673 /* Customised helper to load the download host URI template
674 * directly from the setup tool's resource data section.
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;
685 int set_transit_path( const char *path, const char *file, char *buf = NULL )
687 /* Helper to define the transitional path name for downloaded files,
688 * used to save the file data while the download is in progress.
690 static const char *transit_dir = "/.in-transit";
691 return mkpath( buf, path, file, transit_dir );
694 int pkgInternetStreamingAgent::Get( const char *from_url )
696 /* Download a file from the specified internet URL.
698 * Before download commences, we accept that this may fail...
702 /* Set up a "transit-file" to receive the downloaded content.
704 char transit_file[set_transit_path( dest_template, filename )];
705 int fd; set_transit_path( dest_template, filename, transit_file );
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 )
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".
716 if( (dl_host = pkgDownloadAgent.OpenURL( from_url )) != NULL )
718 //dmh_printf( "success\n" );
719 if( pkgDownloadAgent.QueryStatus( dl_host ) == HTTP_STATUS_OK )
721 /* With the download transaction fully specified, we may
722 * request processing of the file transfer...
724 if( (dl_meter = pkgDownloadMeter::UseGUI()) != NULL )
726 /* ...with progress monitoring delegated to the GUI's
727 * dialogue box, when running under its auspices...
730 filename, pkgDownloadAgent.QueryContentLength( dl_host )
732 dl_status = TransferData( fd );
735 { /* ...otherwise creating our own TTY progress monitor,
736 * when running under the auspices of the CLI.
738 pkgDownloadMeterTTY download_meter(
739 from_url, pkgDownloadAgent.QueryContentLength( dl_host )
741 dl_meter = &download_meter;
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.
749 dl_status = TransferData( fd );
752 else DEBUG_INVOKE_IF( DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ),
753 dmh_printf( "OpenURL:error:%d\n", GetLastError() )
756 /* We are done with the URL handle; close it.
758 pkgDownloadAgent.Close( dl_host );
760 //else dmh_printf( "failed\n" );
762 /* Always close the "transit-file", whether the download
763 * was successful, or not...
768 * When successful, we move the "transit-file" to its
769 * final downloaded location...
771 rename( transit_file, dest_file );
773 /* ...otherwise, we discard the incomplete "transit-file",
774 * leaving the caller to diagnose the failure.
776 unlink( transit_file );
778 //else dmh_printf( "failed\n" );
780 /* Report success or failure to the caller...
785 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
787 void pkgActionItem::PrintURI
788 ( const char *package_name, int (*output)( const char * ) )
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...
794 if( ! match_if_explicit( package_name, value_none ) )
796 /* ...applicable only to real (i.e. not meta) packages.
798 * We begin by retrieving the URI template associated with
799 * the specified package...
801 const char *url_template = get_host_info( Selection(), uri_key );
802 if( url_template != NULL )
804 /* ...then filling in the package name and preferred mirror
805 * assignment, as if preparing to initiate a download...
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 );
811 /* ...then, rather than actually initiate the download,
812 * we simply write out the generated URI to stdout.
814 output( package_url );
819 #endif /* PACKAGE_BASE_COMPONENT */
821 void pkgActionItem::DownloadSingleArchive
822 ( const char *package_name, const char *archive_cache_path )
824 pkgInternetStreamingAgent download( package_name, archive_cache_path );
826 /* Check if the required archive is already available locally...
828 if( ((flags & ACTION_DOWNLOAD) == ACTION_DOWNLOAD)
829 && ((access( download.DestFile(), R_OK ) != 0) && (errno == ENOENT)) )
831 /* ...if not, ask the download agent to fetch it,
832 * anticipating that this may fail...
834 flags |= ACTION_DOWNLOAD_FAILED;
835 const char *url_template = get_host_info( Selection(), uri_key );
836 if( url_template != NULL )
838 /* ...from the URL constructed from the template specified in
839 * the package repository catalogue (configuration database).
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 );
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.
850 pkgDownloadAgent.SetRetryOptions( Selection(), url_template );
851 if( download.Get( package_url ) > 0 )
853 * Download was successful; clear the pending and failure flags.
855 flags &= ~(ACTION_DOWNLOAD | ACTION_DOWNLOAD_FAILED);
857 /* Diagnose failure; leave pending flag set.
859 dmh_notify( DMH_ERROR,
860 "Get package: %s: download failed\n", package_url
864 /* Cannot download; the repository catalogue didn't specify a
865 * template, from which to construct a download URL...
867 dmh_notify( DMH_ERROR,
868 "Get package: %s: no URL specified for download\n", package_name
872 /* There was no need to download any file to satisfy this request.
874 flags &= ~(ACTION_DOWNLOAD);
877 void pkgActionItem::DownloadArchiveFiles( pkgActionItem *current )
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...
884 while( current != NULL )
886 /* ...while we haven't run off the end, and collecting any diagnositic
887 * messages relating to any one package into a common digest...
889 dmh_control( DMH_BEGIN_DIGEST );
890 if( (current->flags & ACTION_INSTALL) == ACTION_INSTALL )
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.
898 const char *package_name = current->Selection()->ArchiveName();
900 /* An explicit package name of "none" is a special case;
901 * it identifies a "virtual" meta-package...
903 if( match_if_explicit( package_name, value_none ) )
905 * ...which requires nothing to be downloaded...
907 current->flags &= ~(ACTION_DOWNLOAD);
910 /* ...but we expect any other package to provide real content,
911 * for which we may need to download the package archive...
913 current->DownloadSingleArchive( package_name, pkgArchivePath() );
916 /* The current action has no associated "install" requirement,
917 * so neither is there any need to request a "download".
919 current->flags &= ~(ACTION_DOWNLOAD);
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.
925 dmh_control( DMH_END_DIGEST );
926 current = current->next;
930 #if IMPLEMENTATION_LEVEL == PACKAGE_BASE_COMPONENT
932 #define DATA_CACHE_PATH "%R" "var/cache/mingw-get/data"
933 #define WORKING_DATA_PATH "%R" "var/lib/mingw-get/data"
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.
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.
947 #define PKGSTRM_H_SPECIAL 1
950 class pkgInternetLzmaStreamingAgent:
951 public pkgInternetStreamingAgent, public pkgLzmaArchiveStream
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).
959 /* We need a specialised constructor...
961 pkgInternetLzmaStreamingAgent( const char*, const char* );
964 /* Specialisation requires overrides for each of this pair of
965 * methods, (the first from the pkgLzmaArchiveStream base class;
966 * the second from pkgInternetStreamingAgent).
968 virtual int GetRawData( int, uint8_t*, size_t );
969 virtual int TransferData( int );
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).
976 pkgInternetLzmaStreamingAgent::pkgInternetLzmaStreamingAgent
977 ( const char *local_name, const char *dest_specification ):
978 pkgInternetStreamingAgent( local_name, dest_specification ),
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.
989 pkgLzmaArchiveStream( -2 ){}
991 int pkgInternetLzmaStreamingAgent::GetRawData( int fd, uint8_t *buf, size_t max )
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.
998 dl_status = pkgDownloadAgent.Read( dl_host, (char *)(buf), max, &count );
1002 int pkgInternetLzmaStreamingAgent::TransferData( int fd )
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.
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) );
1014 DEBUG_REQUEST( DEBUG_TRACE_INTERNET_REQUESTS ) && (dl_status == 0),
1015 dmh_printf( "\nInternetReadFile:download error:%d\n", GetLastError() )
1020 EXTERN_C const char *serial_number( const char *catalogue )
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).
1027 pkgXmlDocument src( catalogue );
1030 && ((issue = src.GetRoot()->GetPropVal( issue_key, NULL )) != NULL) )
1032 * Found an issue number; return a copy...
1034 return strdup( issue );
1036 /* If we get to here, we couldn't get a valid issue number;
1037 * whatever the reason, return NULL to indicate failure.
1042 void pkgXmlDocument::SyncRepository( const char *name, pkgXmlNode *repository )
1044 /* Fetch a named package catalogue from a specified Internet repository.
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.
1051 const char *url_template;
1052 if( (url_template = repository->GetPropVal( uri_key, NULL )) != NULL )
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).
1059 pkgInternetLzmaStreamingAgent download( name, DATA_CACHE_PATH "%/M/%F.xml" );
1061 /* Construct the full URI for the master catalogue, and stream it to
1062 * a locally cached, decompressed copy of the XML file.
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 );
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
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
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.
1085 const char *repository_version, *working_version;
1086 if( (repository_version = serial_number( download.DestFile() )) != NULL )
1088 /* Identify the location for the working copy, (if it exists).
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 );
1094 /* Compare issue serial numbers...
1096 if( ((working_version = serial_number( working_copy )) == NULL)
1097 || ((strcmp( repository_version, working_version )) > 0) )
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.
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.
1110 unlink( working_copy );
1111 rename( download.DestFile(), working_copy );
1114 /* The issue numbers, returned by the serial_number() function, were
1115 * allocated on the heap; free them to avoid leaking memory!
1117 free( (void *)(repository_version) );
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.
1123 if( working_version != NULL )
1124 free( (void *)(working_version) );
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
1133 unlink( download.DestFile() );
1137 #endif /* PACKAGE_BASE_COMPONENT */
1139 /* $RCSfile$: end of file */