Home > Articles > Web Development > Perl

Viewing Compressed Files from the Web

📄 Contents

  1. Viewing File Contents
  2. Conclusion
  3. Listing
Files can clutter up your system worse than empty cola cans and sticky notes clutter your workspace. How can you manage these text files easily while saving disk space, using the Web as a way to view them? With the power of Perl.
Like this article? We recommend

Like this article? We recommend

What do you get when you cross compressed text files, Perl, and the web? An easy way to save disk space, unclutter directories, and view contents of compressed files on the internet.

Files, files, and more files!

If you're like me, you have many text files laying about. System logs, server logs, script logs, security logs, and even some log logs. Plus, you may also have various gzipped files laying about. And, like me, you would rather have a nice web front-end to these files instead of having to use a shell interface, as well as having these files take up less space on your hard drive.

To give you an example, I keep all my web server logs, I have logs which monitor my home servers uptime, I have cron logs, and some gzipped software which I keep around to peek at the source files from time to time. All these files can really take up a lot of space as time goes on. How can I keep these files manageable, while freeing up some disk space? Three words; compression, Perl, web!

Compression of files is not only a useful way to distribute batches of files, but it is also a handy way to save space on your machine. There are various compression programs out there, but we will be dealing with files which have been passed through one of the most popular compression utility, gzip. The tar utility will take multiple files and bundle them together, without compressing them. Then, when the tar file is gzipped, it compresses that single file (of files). The script discussed in this article will work with both file formats.

Perl, of course, is a very powerful scripting language. One of the great things about Perl is if there is something you want to do, it is likely someone else already thought of doing it. Dealing with tar/gzipped files is one of those things. A simple search on the CPAN shows the Archive::Tar module is just what we need to accomplish our goal. Since this module does not come with the standard distribution of Perl, you will need to install it. There is also an Archive::Zip module for handling zipped files, but this article will be concentrating on tar/gzipped files.

The web is a great medium to emulate what is on a filesystem. So, this makes it the perfect medium to peek into tar/gzipped files withough having to manually interact with the shell. The web is also good for those who do not have shell access, or those who don't always have access to their shell.

So, with these three elements, we will construct a CGI script, using Perl, which will allow someone to peek into tar and gzip files, as well as the files contained within them. The following program will read in specified directories looking for certain file extensions, and display those files as hyperlinks, to a web client. When a hyperlink is chosen, the contents of the archive file will be displayed, with each file being a hyperlink. Then, when a file is chosen (or, clicked on), the contents of that file will be displayed to the web client. You will have a looking glass into the text archives on your disk, while saving disk space.

Viewing File Contents

Let's assume we have some compressed files in various locations on a system we want to be able to view over the web. In essence, we have saved some space by compressing the files, and now we can save some time by making these files browsable from the web.

Perl to the rescue! As you will see, by using a combination of the CGI.pm module, and the Archive::Tar module we will be able to view our compressed files in only 52 lines of Perl. Let's begin.

     01: #!/usr/bin/perl -wT

     02: use strict;
     03: use CGI qw(:standard);
     04: use Archive::Tar;
     05: use File::Basename;

Lines 1 through 5 begin the script by turning on warnings, and taint checking. We also help preserve some sanity by using the strict pragma. We use the CGI.pm module, which we will use to get the incoming parameters, as well as use to generate some HTML for us. The Archive::Tar module is what will actually deal with the compressed files. On its own, the Archive::Tar module will handle tar files. If you wish to also use gzipped files, you will need to install the Compress::Zlib module as well. Luckily, you would not need to change your code, since Archive::Tar uses Compress::Zlib in the background. Finally, we pull in the File::Basename module, which we will use to get the name of our script for when we create hyperlinks to itself.

We now have all the tools we need to begin.

     06: my @DIRS = qw{tars /tmp};
     07: my $SCRIPT = basename $0;
     08: my $tar;

     09: my %actions = ('list_archives' => \&list_archives,
              ''       => \&list_archives,
              'show_file'   => \&show_file,
              'show_content' => \&show_content,
              );

Lines 6 to 9 define our global variables. The @DIRS variable is an array of the directory locations where you wish to see the compressed files. In this case, we are looking in the 'tars' directory (off of the current working directory), as well as the '/tmp' directory. More directories could be added, or removed at your own whims.

The $SCRIPT variable gets it's value from the basename() method of File::Basename module. By passing it $0, which is the name and path of the currently running script, it will return just the filename. You will see how we use this later to create hyperlinks. A benefit of doing it like this is that you do not have to hard code a script name in the hyperlinks. Hard coding things like that can make future maintainance more of a pain.

The $tar variable is initialized, with no value. We will be using this variable to hold the name of the file we want to look at, but more on that in a moment.

Finally, we initialize the %actions hash. The hyperlinks we later create will have an 'action' parameter. This hash contains the allowed actions we can do, and the subroutine which will be performing the requested action. If someone requests an action which is not a key in this hash, they will see an error.

     10: print header;

Line 10 simply uses the CGI::header() method to print out the standard header.

     11: my $action = param('action');

Line 11 utilizes the CGI::param() method to get the value, if any, of the 'action' parameter passed in the URI of the request. The value of this is then put into the $action variable.

     12: if (param('tar')) {
     13:   $tar = param('tar');
     14:   $tar =~ s!\.\.?/!!g;
     15: }

Lines 12 to 15 check if there is a 'tar' parameter being passed to the script via the requesting URI. If there is, the value is put into the $tar variable, and then the $tar variable is stripped of all occurences of ./ and ../. We expect that the $tar parameneter is going to contain a file path, and name, of a tar (or gzipped) file. But, we don't want people to try to trick the script into opening files not in the directories we have listed in @DIRS. By stripping out those two sequences, we make sure that someone isn't trying to backtrack directories and open arbitrary files you may have on your system. There are really two ways to handle this; 'collapse' the directory path, as I am doing here, or reject the bad path altogether. I chose to collapse the path simply to be lazy. The same end is achieved both ways, no directory backtracking.

     16: if (exists $actions{$action}) {
     17:   $actions{$action}->();
     18: }else{
     19:   print qq{Sorry, '$action' isn't supported.<BR>};
     20: }

Lines 16 through 20 look to see of the requested action is an action which we have defined. If so, line 17 calls the subroutine reference which is the value of the proper entry in %actions. If we do not support the action which was requested, line 19 will print an error to the screen.

     21: sub list_archives {
     22:   print h2("List of files");

     23:   for my $dir (@DIRS) {
     24:       print qq{Directory: $dir<br>\n};

     25:       opendir(DIR, $dir) or print qq{$!<p>\n} and next;

     26:       my @files = grep {/\.tar(?:\.gz)?$/} readdir(DIR);
     27:       for (@files) {
     28:           (my $short_name = $_) =~ s/\.tar.*$//;
     29:           print a({-href=>"tar.cgi?action=show_file
&tar=$dir/$_"},$short_name), br;
     30:       }
     31:       closedir DIR;
     32:       print p;
     33:   }
     34: }

Lines 21 to 34 make up the list_archives() subroutine. This subroutine will be called when we are to list all of the .tar* files in the directories contained in @DIRS. We begin by displaying a heading for the page, on line 22. Then, we begin to look through the @DIRS array, initializing the $dir variable each fime with the directory name we are currently looking through. Line 24 prints out the directory name we are about to get a listing for. Line 25 uses the opendir() function to open a handle, DIR, to read in the file contents of the directory. If there is a problem opening the directory, the error, such as "No such file or directory" will be printed, and the next will send the iteration to the next directory.

Line 26 creates the @files array by grepping through the output of readdir(DIR), which would be the file contents of the directory. The grep is looking for all files which end in .tar or .tar.gz. If the filename matches that patter, it is added to the @files array.

Line 27 now begings to loop through the filenames. The name of the file then has the extension taken off, for display purposes, and the CGI::a() method, on line 29, is used to create a hyperlink back to this script. The link will pass the action parameter with the action of show_files, as well as a tar parameter, whose value is that of the location of the requested file. This link will allow the user to choose the file to look at (since the extension is removed, it would look like a directory name). If a user didn't know what was under the hood of this CGI, it would appear as if they were traversing a directory listing, as opposed to peering inside of compressed files.

Lines 31 and 32 close the directory handle, and print an HTML <p> tag to finish off the subroutine.

     35: sub show_file {
     36:   print h2("Contents of $tar:");
     37:   print qq{Sorry, '$tar' does not exist.} 
and return unless -e $tar;
     38:   my @files = Archive::Tar->list_archive($tar);

     39:   for (@files) {
     40:       if (/\/$/) {
     41:           print qq{$_<br>\n};
     42:       }else{
     43:           print '<dd>', a({-href => "tar.cgi?action=
show_content&file=$_&tar=$tar"}, $_), '</dd>';
     44:       }
     45:   }
     46: }

Line 35 begins the show_file() subroutine. This subroutine will get called when a link displayed from the list_archives() subroutine is clicked. This subroutine will take the file name, and display a list of the files within the current file. Line 36 simply shows a heading. Line 37 checks for the existence for the tar file we want to peek inside of. If it does not exists, an error message is displayed and we return from the subroutine. This should only occur when someone attempts to alter the URI to have a different file name. Line 38 uses the Archive::Tar-list_archive()> method, with the one argument being the location of the wanted file, to get a list of files in the tarball.

Lines 39 to 45 loop through the list of files, which was assigned to @files. If the filename ends with a /, then it is a directory. We check for this on line 39, and if it matches, we disply only the name of the directory on line 41. Since we are peeking inside the tar file, and not actually extracting the contents, we cannot use -d to check if what we have is a directory or not. That is why we use the pattern match. If there is no trailing /, then we are dealing with a filename. Line 43 prints out a hyperlink with the action show_content, which we will cover in a moment. The link also passes the file parameter, which is the name of the file we want to see, and the tar parameter; which is the tar file. We also slightly indent the filename, simply for aesthetic reasons.

     47: sub show_content {
     48:   my $file = param('file');

     49:   my $tar_obj = Archive::Tar->new($tar);
     50:   print qq{<pre> } . $tar_obj->get_content($file) . qq{</pre>};
     51: }

Lines 47 to 51 comprise the show_content() subroutine. This is the final subroutine of the script. This subroutine will display the contents of the file the user selected. Firstly, line 49 gets the name of the file which was sent in QUERY_STRING. Line 49 then creates a new Archive::Tar object, $tar_obj. The name of the file we will be working with is passed as an arguement to new(), which will in turn open and read the file contents into memory. Line 50 displays the contents of the requested file. This is done by printing the output of Archive::Tar's get_contents() object method between a set of HTML <pre> tags. Since we are expecting only text files for this application, this should display the text nicely in the web client.

     52: print p, a({-href=>$SCRIPT},"Home");

Finally, line 52 ends the script by displaying a link back to the original listing of filenames. This will be displayed on every page.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020