TweetFollow Us on Twitter

FTP Client in TCL-TK

Volume Number: 14 (1998)
Issue Number: 2
Column Tag: Alternate Environments

An FTP Fetch Client in Tcl/Tk

by Bruce O'Neel, Laurel MD

A light introduction to this powerful, multi-platform scripting language

Overview

Tcl/Tk (pronounced "tickle tee-kay") is a scripting language written by Dr. John Ousterhout while he was a professor at the University of California at Berkeley. Tcl can either be a standalone shell where you issue commands (like those of unix or the MPW shell), or it can be a library which you embed into your compiled program and use to issue commands. Tk is an extension to Tcl which provides graphical interface Tcl commands enabling you to write event driven programs with graphical interfaces.

Tcl/Tk has been very popular in the unix world for a long time and has recently been ported to Mac OS and Win95/NT. As of version 8.0 of Tcl/Tk, the Mac OS and Win95/NT ports have a native look and feel on their respective platforms. This article is going to provide a brief overview of Tcl/Tk and then present a demonstration Tcl/Tk program to fetch files using FTP.

Tcl/Tk Overview

Why is Tcl/Tk interesting? First, it is a dynamic scripting language. At run-time your scripts are byte compiled and run. You can get the names of procedures and variables at run-time; you can define new commands and new control statements at run-time; you can load new source code at run-time; and you can extend Tcl with your own shared libraries at run-time. Second, you can produce Mac like interfaces using the native port of Tk and you can do this quickly and interactively. Think of it as rapid prototyping for the Mac in a free language. Third, you can write scripts which can be moved unchanged from Mac OS to Win95/NT and most unix variants. Finally, you can easily write extensions to Tcl in any compiled language on the Mac, and they can either call and be called by C or produce shared libraries. These extensions also can be cross-platform if written to be portable. As an example, a group of people at NASA's Goddard Space Flight Center have written an extension to Tcl which reads and writes a file format called FITS used in astronomy ftp://legacy.gsfc.nasa.gov/software/ftools/release/other/fitstclmac-src.sit.hqx.

There are a few notes on Tcl's syntax that will make reading the code easier. First, remember that Tcl works by string substitution and that, from your point of view, everything is a string. $varname means look up the value that is currently assigned to a variable and put that string in place of $varname. [command arg arg] means execute what ever is between the square brackets and substitute the value in place of [command arg arg]. Finally, curly braces are used around parts of code you want to execute later and defer evaluation until sometime in the future.

An FTP Client

I thought that a good demo of Tcl/Tk for the Mac would be an FTP client. Now, I didn't want to rewrite Fetch or Anarchie, but, I did want a useful example. The example program works but there are many features left for the reader to complete and the sample probably won't work unless you FTP to a unix system. One develops a lot of respect for Anarchie or Fetch when you try to repeat their author's work.

So, even though this is just a simple example, what made it good for Tcl/Tk? First, it was quick and easy to write. I took about 4-6 hours to write most of the code, with a little bit of time to clean things up for publication. Second, the resulting executable is small at around 27 Kbytes and the UI is very Mac like. Third the same source worked on more than one system. I was also able to run this on a unix system pretty much unchanged for additional testing and on the unix system it looked like I was running a Motif application. Finally I wanted a GUI and TCP/IP sockets in my program and Tcl/Tk has all of this easily built in, debugged, and well documented. Plus, you can experiment interactively with your code rather than compile, link, run, crash, debug,and edit as you must normally do.

There are two downsides to Mac Tcl/Tk applications. The first is that you have to install Tcl/Tk. The small application depends on some shared libraries, but, you could avoid the need to already have installed Tcl/Tk by using the non-shared version. The second downside is that the current version requires quite a bit of memory. The default is 4mb but you might have to bump this up if your programs crash. Many crashes are caused by running out of memory.

Displaying aWindow

The first thing the user sees when they start the program is a dialog produced by the new_connection proc, listed below. The dialog looks like

Figure 1. Open Connection Dialog.

Because Tcl/Tk is interactive, you could download it from http://sunscript.sun.com and type in each following command and watch what happens as you go. This is a very quick way to learn how Tcl/Tk works.

new_connection
This is the main dialog the user interacts with and an example of Tcl/Tk
programming. This asks the user for their hostname, username (optional),
password (optional), and directory to connect to. When they click the
connect button, it brings up a directory list of that directory.

# Procedure to open a new connection.
proc new_connection {} {
  
  # so we can access the global variable FTP
  global FTP

  # This sets the variable named t to the result of the 
  # toplevel command
  # toplevel, like all Tk Widget creation commands returns 
  # the name of the widget,
  # .new_connection in this case, as it's result.
  set t [toplevel .new_connection -menu .menubar]
  wm title $t "Open Connection"
  
  # create a text label
  label $t.title -text "Open a new FTP connection"
  # grid is a geometry manager. This puts the title on the 
  # screen.
  grid $t.title -columnspan 2

  label $t.hostl -text "Hostname:"
  # associate the variable FTP(hostname) with a text entry 
  # area on the screen.
  # note that there is not $ before FTP(hostname)
  entry $t.hoste -textvariable FTP(hostname)
  grid $t.hostl $t.hoste

  label $t.userl -text "Username:"
  entry $t.usere -textvariable FTP(username)
  grid $t.userl $t.usere
  
  label $t.passl -text "Password:"
  # -show * echos * rather than the user's keystrokes
  entry $t.passe -textvariable FTP(password) -show *
  grid $t.passl $t.passe
  
  label $t.dirl -text "Directory:"
  entry $t.dire -textvariable FTP(directory)
  
  # create a button which when it runs the command up_dir
  button $t.dirup -text "Up" -command "up_dir" 
  grid $t.dirl $t.dire $t.dirup
  
  # put up two radio buttons to set datamode. Tied together 
  # by the -variable option.
  radiobutton $t.binary -variable FTP(mode) -text Binary \
    -value Binary
  radiobutton $t.ascii -variable FTP(mode) -text Ascii \
    -value Ascii
  label $t.datamode -text "Data Mode: "
  grid $t.datamode $t.binary $t.ascii
  
  # frames hold things
  frame $t.direc
  label $t.direc.title -text "Remote Directory"
  # pack is another geometry manager and puts the title at 
  # the top of this frame
  pack $t.direc.title -side top
  # the following three commands set up a text box and two 
  # scroll bars
  set FTP(listbox) [listbox $t.direc.list \
    -xscrollcommand [list $t.direc.xscroll set] \
    -yscrollcommand [list $t.direc.yscroll set]]
  scrollbar $t.direc.xscroll -orient horizontal \
    -command [list $t.direc.list xview]
  scrollbar $t.direc.yscroll -orient vertical \
    -command [list $t.direc.list yview]
  # these pack commands put the listbox and the scrollbars on 
  # the screen
  pack $t.direc.xscroll -side bottom -fill x
  pack $t.direc.yscroll -side right -fill y
  pack $t.direc.list -side left -fill both -expand true
  
  # put the whole frame with the remote directory listing on 
  # the screen
  grid $t.direc -columnspan 2
  
  # attach the event of double mouse button 1 (on the Mac, 
  # double click) when within
  # the widget $t.direc.list to the event of running the 
  # command get_file_or_dir.
  # In other words, this sets up a routine such that when you 
  # double click 
  # in the list box your routine get_file_or_dir is called
  bind $t.direc.list <Double-1> {get_file_or_dir}

  button $t.connect -text Connect \
    -command "get_dir $t.direc.list"
  
  # destroy deletes a widget and all of it's children
  button $t.cancel -text Cancel -command "destroy $t"
  grid $t.connect $t.cancel
}

This code doesn't produce the nicest looking dialog, but, it's functional. It would be much prettier if I went through and added space around widgets and added colors. Note that the functions of the dialog are quite separate from the layout. This allows me to go through and change the design of the dialog without changing the supporting code.

Connecting to the Server

Once the user has filled out the connection dialog and clicked Connect it's time to get a directory listing. The bit of code which talks to the remote FTP server and gets directory looks like this:

ftp_get_dir
This bit of code reads the global FTP array variable and returns as its
result the directory listing from the remote system. It connects to
FTP(hostname) as user FTP(username), or anonymous if blank, using a
password of FTP(password), or user@host if blank. It then changes directory
to FTP(directory) and gets that directory and returns the result as a big
string.

# The guts of getting an FTP directory. Note that this is 
# the netscape connect, do 
# something, and quit. Really inefficient but much easier to 
# implement.
proc ftp_get_dir {} {
  global FTP
  set FTP(data_sock) 0

  update_status \
    "Getting directory from site $FTP(hostname)"

  update_status "Establishing FTP connection ..."
  
  # connect to the remote system
  set FTP(ftp_sock) [socket $FTP(hostname) ftp]
  fconfigure $FTP(ftp_sock) -blocking 0 -buffering none
  
  # call a routine ftp_read_line when the remote socket is 
  # readable
  fileevent $FTP(ftp_sock) readable ftp_read_line

  if {[ftp_read] > 3} {
    return
  }

  update_status "Logging in ..."

  # send the username and password
  if {[string compare $FTP(username) ""]} {
    puts $FTP(ftp_sock) "USER $FTP(username)"
  } else {
    puts $FTP(ftp_sock) "USER anonymous"
  }
  if {[ftp_read] > 3} {
    return
  }

  if {[string compare $FTP(password) ""]} {
    puts $FTP(ftp_sock) "PASS $FTP(password)"
  } else {
    puts $FTP(ftp_sock) "PASS user@hostname"
  }
  if {[ftp_read] > 3} {
    return
  }

  # change to the user selected directory or /
  if {[string compare $FTP(directory) ""]} {
    puts $FTP(ftp_sock) "CWD $FTP(directory)"
  } else {
    puts $FTP(ftp_sock) "CWD /"
  }
  if {[ftp_read] > 3} {
    return 
  }

  update_status "Setting up for transfer ..."

  # transfer directories in ascii mode
  puts $FTP(ftp_sock) "TYPE A"
  if {[ftp_read] > 3} {
    return
  }

  # get a server socket on our system so that the remote 
  # system can send
  # us the directory listing
  update_status "Opening server port ..."

  set serv_sock [socket -server notify_connect 0]

  update_status "Setting up to retrieve directory ..."
  
  set hostip [lindex [fconfigure $FTP(ftp_sock) -sockname] 0]
  set serv_port [lindex [fconfigure $serv_sock -sockname] 2]

  # expr is how we do math
  set serv_up [expr "int($serv_port/256)"]
  set serv_lw [expr "$serv_port-$serv_up*256"]
  regsub -all {\.} $hostip "," hostip

  # send the port command to the remote system
  puts $FTP(ftp_sock) "PORT $hostip,$serv_up,$serv_lw"
  if {[ftp_read] > 3} {
    close $serv_sock
    fileevent $FTP(ftp_sock) readable ""
    close $FTP(ftp_sock)
    return
  }

  # send the list command
  puts $FTP(ftp_sock) "LIST"

  if {[ftp_read] > 3} {
    close $serv_sock
    fileevent $FTP(ftp_sock) readable ""
    close $FTP(ftp_sock)  
    return
  }

  update_status "Retrieving dir ..."

  fconfigure $FTP(data_sock) -translation auto

  # keep reading on the server socket until end of file.
  while { ! [eof $FTP(data_sock)] } {
    set buf [read $FTP(data_sock) 1024]
    append result $buf
  }

  # clean up and exit
  update_status "Closing connection ..."

  puts $FTP(ftp_sock) "QUIT"
  fileevent $FTP(ftp_sock) readable ""
  close $FTP(ftp_sock)
  close $serv_sock
  close $FTP(data_sock)
  return $result
}

This bit of code talks to a remote system and implements enough of the FTP protocol to get a file listing. Basically it sends a USER command, followed by a PASS command to log in with a user name and a password. Then it sends a CWD command to change to the proper directory. Next it sends a PORT command, probably the only tricky bit. The FTP protocol uses two channels. The first is the command/result channel which is where we send commands such as USER and PASS and get responses. The second is the data channel which is where we transfer files. This is different from the http protocol where we would use the same channel for both transfers.

To request a file or directory listing from the remote system we set up a server port on the local system and tell the remote system what that port number is with the PORT command. The remote system opens a connection to that port and sends the remote file or directory listing over that connection. The PORT command has a slightly odd syntax of the form A,B,C,D,E,F where the local numeric IP address is A.B.C.D and E is the port address high byte and F is the port address low byte. Once we've gotten the port command sent, we send the LIST command. The remote system opens a socket to the port we gave it and sends the result. Once we see and end of file on our server socket we are done and can send the QUIT command. You can experiment with the FTP protocol by using a telnet client to connect to port 21 on most systems. You can also get ftp://nic.merit.edu/documents/rfc/rfc0959.txt and read all of the gory details.

Retrieving a file is just as easy as getting a listing. The routine ftp_get_file is almost identical to ftp_get_dir, but instead of using a LIST command to get a directory listing, we use a RETR command to get a remote file. Also, we write the file out to disk rather than returning it's contents as a string.

Adding a Menubar

Up to now all of the code has been generic Tcl/Tk. While it's nice to produce portable applications, we use Macs because we like them and we'd like our applications to look Mac-like. Tcl/Tk 8.0 has some nice features built in that we can use to make the application look more like a Mac. If we create a menu widget called say .menubar, and then add an entry to that called .menubar.apple, items on this menu will be in the Apple menu. So, we add a menubar as follows:

part of the main program 
This will add the Mac menus such that they work like Mac menus. We
create a menubar named .menubar and then add Apple and File entries
to it. The Apple entrys will appear under the Apple menu as you'd expect
and the File menu will be the first menu after the Apple menu. We'll add
an accelerator to the Quit menu option with Meta-Q which will be
translated to Command-Q on the Mac.

# make a menubar
menu .menubar -tearoff 0

# add the file menu
.menubar add cascade -menu .menubar.file -label "File"
menu .menubar.file -tearoff 0

# add the apple menu
.menubar add cascade -menu .menubar.apple  
menu .menubar.apple -tearoff 0
# add the about entry
.menubar.apple add command -label "About..." \
  -command aboutbox

# add entries to the file menu
.menubar.file add command -label "New Connection..." \
  -command new_connection
.menubar.file add separator
# this will be the normal mac quit keyboard acclerator
.menubar.file add command -label "Quit" \
  -command exit -accelerator "Meta-Q"

# make the menu the menu for the toplevel . window. Whenever
# the . window is the frontmost window then the menubar 
# .menubar will be the menu at the top of the screen.

. configure -menu .menubar

The only other Mac specific command is console hide at the end of the program. This prevents the Tcl console from appearing. The Tcl console is where you would type Tcl commands if you were using Tcl interactively.

The last thing to do to generate a standalone Mac executable is to drag your Tcl source file onto the program Drag & Drop Tclets and answer the questions. This little program will build a Tcl executable which can be double-clicked to run our Tcl script.

Conclusion

After reading this article you should have gained an appreciation for Tcl/Tk and some things you can do with it on the Mac. It's also possible to control other programs with the TclAppleScript extension, which ships with Tcl/Tk 8.0. This allows you to use Tcl to tie together multiple programs as you can with AppleScript. Now that Tcl/Tk has native look-and-feel, the Mac Tcl scripts look like Mac programs and Tcl/Tk gives you a quick way to write Mac programs.

Bibliography and References

  • Ousterhout, John K. Tcl and the Tk Toolkit, Addison-Wesley, 1994.
  • Welch, Brent B. Practical programming in Tcl & Tk, Prentice Hall, 1997.

For more information you should check the main site at http://sunscript.sun.com/ and an excellent overview paper on Tcl/Tk and scripting languages is from http://www.sunlabs.com/~ouster/scripting.html.


Bruce O'Neil beoneel@macconnect.com spends his work time working on astrophysics satellites and his spare time playing with his lovely wife and children. What time is left is devoted to his PowerBook.

 
AAPL
$524.94
Apple Inc.
+5.93
MSFT
$40.01
Microsoft Corpora
-0.39
GOOG
$536.10
Google Inc.
-20.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

VMware Fusion 6.0.3 - Run Windows apps a...
VMware Fusion allows you to create a Virtual Machine on your Mac and run Windows (including Windows 8.1) and Windows software on your Mac. Run your favorite Windows applications alongside Mac... Read more
Tweetbot 1.5.1 - Popular iOS twitter cli...
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more

Latest Forum Discussions

See All

This Week at 148Apps: April 14-18, 2014
Spring Into Our App Reviews   | Read more »
Have a Special Dead Trigger 2 Easter Bas...
Have a Special Dead Trigger 2 Easter Basket Full of Goodies, Courtesy of Madfinger Games Posted by Rob Rich on April 18th, 2014 [ permalink ] Dead Trigger 2 | Read more »
Almost All of Playdek’s Library is on Sa...
Almost All of Playdek’s Library is on Sale Right Now, and You Should Check it Out Posted by Rob Rich on April 18th, 2014 [ permalink ] Playdek has released quite a few great iOS ports of board and card games over the years, and now most of them... | Read more »
Zynga Launches Brand New Farmville Exper...
Zynga Launches Brand New Farmville Experience with Farmville 2: Country Escape Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
David. Review
David. Review By Cata Modorcea on April 18th, 2014 Our Rating: :: MINIMALISTIC IN A DIFFERENT WAYUniversal App - Designed for iPhone and iPad David is a minimalistic game wrapped inside of a soothing atmosphere in which the hero... | Read more »
Eyefi Unveils New Eyefi Cloud Service Th...
Eyefi Unveils New Eyefi Cloud Service That Allows Users to Share Media Across Personal Devices Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Tales from the Dragon Mountain: The Lair...
Tales from the Dragon Mountain: The Lair Review By Jennifer Allen on April 18th, 2014 Our Rating: :: STEADY ADVENTURINGiPad Only App - Designed for the iPad Treading a safe path, Tales from the Dragon Mountain: The Lair is a... | Read more »
Yahoo Updates Flickr App with Advanced E...
Yahoo Updates Flickr App with Advanced Editing Features and More Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
My Incredible Body - A Kid's App to...
My Incredible Body - A Kid's App to Learn about the Human Body 1.1.00 Device: iOS Universal Category: Education Price: $2.99, Version: 1.1.00 (iTunes) Description: Wouldn’t it be cool to look inside yourself and see what was going on... | Read more »
Trials Frontier Review
Trials Frontier Review By Carter Dotson on April 18th, 2014 Our Rating: :: A ROUGH LANDINGUniversal App - Designed for iPhone and iPad Trials Frontier finally brings the famed stunt racing franchise to mobile, but how much does its... | Read more »

Price Scanner via MacPrices.net

Deal Alert! 13-inch MacBook Pro on sale for $...
Best Buy has the 13″ 2.5GHz MacBook Pro on sale for $999.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $200 off MSRP. Price is valid... Read more
Free HopTo 2.2 Helps Enhance Your Productivit...
The HopTo app helps you do more on your iPad by providing more and easier adaccess to files and documents. Version 2.2 adds Egnyte and HopTo’s Mac OSX File Connector. If you already have the hopTo... Read more
National Distracted Driving Awareness Month:...
As the country recognizes National Distracted Driving Awareness Month, Sprint is reminding wireless consumers to focus on driving while behind the wheel, to not text or email while driving, and to... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
Abt has the 13″ 2.4GHz 128GB Retina MacBook Pro available for $1229 including free shipping. Their price is $70 off MSRP. Read more
iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more

Jobs Board

Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Inc. Research Data Specialist - Appl...
…of Worldwide Market Research & Intelligence. The team is responsible for conducting Apple branded consumer market research. It is also responsible for analyzing data Read more
*Apple* Automotive Parts Department position...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive, we Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.