iPXE
ftp.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License as
00006  * published by the Free Software Foundation; either version 2 of the
00007  * License, or any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00017  * 02110-1301, USA.
00018  */
00019 
00020 #include <stdint.h>
00021 #include <stdlib.h>
00022 #include <stdio.h>
00023 #include <string.h>
00024 #include <assert.h>
00025 #include <errno.h>
00026 #include <ctype.h>
00027 #include <byteswap.h>
00028 #include <ipxe/socket.h>
00029 #include <ipxe/tcpip.h>
00030 #include <ipxe/in.h>
00031 #include <ipxe/iobuf.h>
00032 #include <ipxe/xfer.h>
00033 #include <ipxe/open.h>
00034 #include <ipxe/uri.h>
00035 #include <ipxe/features.h>
00036 #include <ipxe/ftp.h>
00037 
00038 /** @file
00039  *
00040  * File transfer protocol
00041  *
00042  */
00043 
00044 FEATURE ( FEATURE_PROTOCOL, "FTP", DHCP_EB_FEATURE_FTP, 1 );
00045 
00046 /**
00047  * FTP states
00048  *
00049  * These @b must be sequential, i.e. a successful FTP session must
00050  * pass through each of these states in order.
00051  */
00052 enum ftp_state {
00053         FTP_CONNECT = 0,
00054         FTP_USER,
00055         FTP_PASS,
00056         FTP_TYPE,
00057         FTP_SIZE,
00058         FTP_PASV,
00059         FTP_RETR,
00060         FTP_WAIT,
00061         FTP_QUIT,
00062         FTP_DONE,
00063 };
00064 
00065 /**
00066  * An FTP request
00067  *
00068  */
00069 struct ftp_request {
00070         /** Reference counter */
00071         struct refcnt refcnt;
00072         /** Data transfer interface */
00073         struct interface xfer;
00074 
00075         /** URI being fetched */
00076         struct uri *uri;
00077         /** FTP control channel interface */
00078         struct interface control;
00079         /** FTP data channel interface */
00080         struct interface data;
00081 
00082         /** Current state */
00083         enum ftp_state state;
00084         /** Buffer to be filled with data received via the control channel */
00085         char *recvbuf;
00086         /** Remaining size of recvbuf */
00087         size_t recvsize;
00088         /** FTP status code, as text */
00089         char status_text[5];
00090         /** Passive-mode parameters, as text */
00091         char passive_text[24]; /* "aaa,bbb,ccc,ddd,eee,fff" */
00092         /** File size, as text */
00093         char filesize[20];
00094 };
00095 
00096 /**
00097  * Free FTP request
00098  *
00099  * @v refcnt            Reference counter
00100  */
00101 static void ftp_free ( struct refcnt *refcnt ) {
00102         struct ftp_request *ftp =
00103                 container_of ( refcnt, struct ftp_request, refcnt );
00104 
00105         DBGC ( ftp, "FTP %p freed\n", ftp );
00106 
00107         uri_put ( ftp->uri );
00108         free ( ftp );
00109 }
00110 
00111 /**
00112  * Mark FTP operation as complete
00113  *
00114  * @v ftp               FTP request
00115  * @v rc                Return status code
00116  */
00117 static void ftp_done ( struct ftp_request *ftp, int rc ) {
00118 
00119         DBGC ( ftp, "FTP %p completed (%s)\n", ftp, strerror ( rc ) );
00120 
00121         /* Close all data transfer interfaces */
00122         intf_shutdown ( &ftp->data, rc );
00123         intf_shutdown ( &ftp->control, rc );
00124         intf_shutdown ( &ftp->xfer, rc );
00125 }
00126 
00127 /*****************************************************************************
00128  *
00129  * FTP control channel
00130  *
00131  */
00132 
00133 /** An FTP control channel string */
00134 struct ftp_control_string {
00135         /** Literal portion */
00136         const char *literal;
00137         /** Variable portion
00138          *
00139          * @v ftp       FTP request
00140          * @ret string  Variable portion of string
00141          */
00142         const char * ( *variable ) ( struct ftp_request *ftp );
00143 };
00144 
00145 /**
00146  * Retrieve FTP pathname
00147  *
00148  * @v ftp               FTP request
00149  * @ret path            FTP pathname
00150  */
00151 static const char * ftp_uri_path ( struct ftp_request *ftp ) {
00152         return ftp->uri->path;
00153 }
00154 
00155 /**
00156  * Retrieve FTP user
00157  *
00158  * @v ftp               FTP request
00159  * @ret user            FTP user
00160  */
00161 static const char * ftp_user ( struct ftp_request *ftp ) {
00162         static char *ftp_default_user = "anonymous";
00163         return ftp->uri->user ? ftp->uri->user : ftp_default_user;
00164 }
00165 
00166 /**
00167  * Retrieve FTP password
00168  *
00169  * @v ftp               FTP request
00170  * @ret password        FTP password
00171  */
00172 static const char * ftp_password ( struct ftp_request *ftp ) {
00173         static char *ftp_default_password = "ipxe@ipxe.org";
00174         return ftp->uri->password ? ftp->uri->password : ftp_default_password;
00175 }
00176 
00177 /** FTP control channel strings */
00178 static struct ftp_control_string ftp_strings[] = {
00179         [FTP_CONNECT]   = { NULL, NULL },
00180         [FTP_USER]      = { "USER ", ftp_user },
00181         [FTP_PASS]      = { "PASS ", ftp_password },
00182         [FTP_TYPE]      = { "TYPE I", NULL },
00183         [FTP_SIZE]      = { "SIZE ", ftp_uri_path },
00184         [FTP_PASV]      = { "PASV", NULL },
00185         [FTP_RETR]      = { "RETR ", ftp_uri_path },
00186         [FTP_WAIT]      = { NULL, NULL },
00187         [FTP_QUIT]      = { "QUIT", NULL },
00188         [FTP_DONE]      = { NULL, NULL },
00189 };
00190 
00191 /**
00192  * Parse FTP byte sequence value
00193  *
00194  * @v text              Text string
00195  * @v value             Value buffer
00196  * @v len               Length of value buffer
00197  *
00198  * This parses an FTP byte sequence value (e.g. the "aaa,bbb,ccc,ddd"
00199  * form for IP addresses in PORT commands) into a byte sequence.  @c
00200  * *text will be updated to point beyond the end of the parsed byte
00201  * sequence.
00202  *
00203  * This function is safe in the presence of malformed data, though the
00204  * output is undefined.
00205  */
00206 static void ftp_parse_value ( char **text, uint8_t *value, size_t len ) {
00207         do {
00208                 *(value++) = strtoul ( *text, text, 10 );
00209                 if ( **text )
00210                         (*text)++;
00211         } while ( --len );
00212 }
00213 
00214 /**
00215  * Move to next state and send the appropriate FTP control string
00216  *
00217  * @v ftp               FTP request
00218  *
00219  */
00220 static void ftp_next_state ( struct ftp_request *ftp ) {
00221         struct ftp_control_string *ftp_string;
00222         const char *literal;
00223         const char *variable;
00224 
00225         /* Move to next state */
00226         if ( ftp->state < FTP_DONE )
00227                 ftp->state++;
00228 
00229         /* Send control string if needed */
00230         ftp_string = &ftp_strings[ftp->state];
00231         literal = ftp_string->literal;
00232         variable = ( ftp_string->variable ?
00233                      ftp_string->variable ( ftp ) : "" );
00234         if ( literal ) {
00235                 DBGC ( ftp, "FTP %p sending %s%s\n", ftp, literal, variable );
00236                 xfer_printf ( &ftp->control, "%s%s\r\n", literal, variable );
00237         }
00238 }
00239 
00240 /**
00241  * Handle an FTP control channel response
00242  *
00243  * @v ftp               FTP request
00244  *
00245  * This is called once we have received a complete response line.
00246  */
00247 static void ftp_reply ( struct ftp_request *ftp ) {
00248         char status_major = ftp->status_text[0];
00249         char separator = ftp->status_text[3];
00250 
00251         DBGC ( ftp, "FTP %p received status %s\n", ftp, ftp->status_text );
00252 
00253         /* Ignore malformed lines */
00254         if ( separator != ' ' )
00255                 return;
00256 
00257         /* Ignore "intermediate" responses (1xx codes) */
00258         if ( status_major == '1' )
00259                 return;
00260 
00261         /* If the SIZE command is not supported by the server, we go to
00262          * the next step.
00263          */
00264         if ( ( status_major == '5' ) && ( ftp->state == FTP_SIZE ) ) {
00265                 ftp_next_state ( ftp );
00266                 return;
00267         }
00268 
00269         /* Anything other than success (2xx) or, in the case of a
00270          * repsonse to a "USER" command, a password prompt (3xx), is a
00271          * fatal error.
00272          */
00273         if ( ! ( ( status_major == '2' ) ||
00274                  ( ( status_major == '3' ) && ( ftp->state == FTP_USER ) ) ) ){
00275                 /* Flag protocol error and close connections */
00276                 ftp_done ( ftp, -EPROTO );
00277                 return;
00278         }
00279 
00280         /* Parse file size */
00281         if ( ftp->state == FTP_SIZE ) {
00282                 size_t filesize;
00283                 char *endptr;
00284 
00285                 /* Parse size */
00286                 filesize = strtoul ( ftp->filesize, &endptr, 10 );
00287                 if ( *endptr != '\0' ) {
00288                         DBGC ( ftp, "FTP %p invalid SIZE \"%s\"\n",
00289                                ftp, ftp->filesize );
00290                         ftp_done ( ftp, -EPROTO );
00291                         return;
00292                 }
00293 
00294                 /* Use seek() to notify recipient of filesize */
00295                 DBGC ( ftp, "FTP %p file size is %zd bytes\n", ftp, filesize );
00296                 xfer_seek ( &ftp->xfer, filesize );
00297                 xfer_seek ( &ftp->xfer, 0 );
00298         }
00299 
00300         /* Open passive connection when we get "PASV" response */
00301         if ( ftp->state == FTP_PASV ) {
00302                 char *ptr = ftp->passive_text;
00303                 union {
00304                         struct sockaddr_in sin;
00305                         struct sockaddr sa;
00306                 } sa;
00307                 int rc;
00308 
00309                 sa.sin.sin_family = AF_INET;
00310                 ftp_parse_value ( &ptr, ( uint8_t * ) &sa.sin.sin_addr,
00311                                   sizeof ( sa.sin.sin_addr ) );
00312                 ftp_parse_value ( &ptr, ( uint8_t * ) &sa.sin.sin_port,
00313                                   sizeof ( sa.sin.sin_port ) );
00314                 if ( ( rc = xfer_open_socket ( &ftp->data, SOCK_STREAM,
00315                                                &sa.sa, NULL ) ) != 0 ) {
00316                         DBGC ( ftp, "FTP %p could not open data connection\n",
00317                                ftp );
00318                         ftp_done ( ftp, rc );
00319                         return;
00320                 }
00321         }
00322 
00323         /* Move to next state and send control string */
00324         ftp_next_state ( ftp );
00325         
00326 }
00327 
00328 /**
00329  * Handle new data arriving on FTP control channel
00330  *
00331  * @v ftp               FTP request
00332  * @v iob               I/O buffer
00333  * @v meta              Data transfer metadata
00334  * @ret rc              Return status code
00335  *
00336  * Data is collected until a complete line is received, at which point
00337  * its information is passed to ftp_reply().
00338  */
00339 static int ftp_control_deliver ( struct ftp_request *ftp,
00340                                  struct io_buffer *iobuf,
00341                                  struct xfer_metadata *meta __unused ) {
00342         char *data = iobuf->data;
00343         size_t len = iob_len ( iobuf );
00344         char *recvbuf = ftp->recvbuf;
00345         size_t recvsize = ftp->recvsize;
00346         char c;
00347         
00348         while ( len-- ) {
00349                 c = *(data++);
00350                 if ( ( c == '\r' ) || ( c == '\n' ) ) {
00351                         /* End of line: call ftp_reply() to handle
00352                          * completed reply.  Avoid calling ftp_reply()
00353                          * twice if we receive both \r and \n.
00354                          */
00355                         if ( recvbuf != ftp->status_text )
00356                                 ftp_reply ( ftp );
00357                         /* Start filling up the status code buffer */
00358                         recvbuf = ftp->status_text;
00359                         recvsize = sizeof ( ftp->status_text ) - 1;
00360                 } else if ( ( ftp->state == FTP_PASV ) && ( c == '(' ) ) {
00361                         /* Start filling up the passive parameter buffer */
00362                         recvbuf = ftp->passive_text;
00363                         recvsize = sizeof ( ftp->passive_text ) - 1;
00364                 } else if ( ( ftp->state == FTP_PASV ) && ( c == ')' ) ) {
00365                         /* Stop filling the passive parameter buffer */
00366                         recvsize = 0;
00367                 } else if ( ( ftp->state == FTP_SIZE ) && ( c == ' ' ) ) {
00368                         /* Start filling up the file size buffer */
00369                         recvbuf = ftp->filesize;
00370                         recvsize = sizeof ( ftp->filesize ) - 1;
00371                 } else {
00372                         /* Fill up buffer if applicable */
00373                         if ( recvsize > 0 ) {
00374                                 *(recvbuf++) = c;
00375                                 recvsize--;
00376                         }
00377                 }
00378         }
00379 
00380         /* Store for next invocation */
00381         ftp->recvbuf = recvbuf;
00382         ftp->recvsize = recvsize;
00383 
00384         /* Free I/O buffer */
00385         free_iob ( iobuf );
00386 
00387         return 0;
00388 }
00389 
00390 /** FTP control channel interface operations */
00391 static struct interface_operation ftp_control_operations[] = {
00392         INTF_OP ( xfer_deliver, struct ftp_request *, ftp_control_deliver ),
00393         INTF_OP ( intf_close, struct ftp_request *, ftp_done ),
00394 };
00395 
00396 /** FTP control channel interface descriptor */
00397 static struct interface_descriptor ftp_control_desc =
00398         INTF_DESC ( struct ftp_request, control, ftp_control_operations );
00399 
00400 /*****************************************************************************
00401  *
00402  * FTP data channel
00403  *
00404  */
00405 
00406 /**
00407  * Handle FTP data channel being closed
00408  *
00409  * @v ftp               FTP request
00410  * @v rc                Reason for closure
00411  *
00412  * When the data channel is closed, the control channel should be left
00413  * alone; the server will send a completion message via the control
00414  * channel which we'll pick up.
00415  *
00416  * If the data channel is closed due to an error, we abort the request.
00417  */
00418 static void ftp_data_closed ( struct ftp_request *ftp, int rc ) {
00419 
00420         DBGC ( ftp, "FTP %p data connection closed: %s\n",
00421                ftp, strerror ( rc ) );
00422         
00423         /* If there was an error, close control channel and record status */
00424         if ( rc ) {
00425                 ftp_done ( ftp, rc );
00426         } else {
00427                 ftp_next_state ( ftp );
00428         }
00429 }
00430 
00431 /** FTP data channel interface operations */
00432 static struct interface_operation ftp_data_operations[] = {
00433         INTF_OP ( intf_close, struct ftp_request *, ftp_data_closed ),
00434 };
00435 
00436 /** FTP data channel interface descriptor */
00437 static struct interface_descriptor ftp_data_desc =
00438         INTF_DESC_PASSTHRU ( struct ftp_request, data, ftp_data_operations,
00439                              xfer );
00440 
00441 /*****************************************************************************
00442  *
00443  * Data transfer interface
00444  *
00445  */
00446 
00447 /** FTP data transfer interface operations */
00448 static struct interface_operation ftp_xfer_operations[] = {
00449         INTF_OP ( intf_close, struct ftp_request *, ftp_done ),
00450 };
00451 
00452 /** FTP data transfer interface descriptor */
00453 static struct interface_descriptor ftp_xfer_desc =
00454         INTF_DESC_PASSTHRU ( struct ftp_request, xfer, ftp_xfer_operations,
00455                              data );
00456 
00457 /*****************************************************************************
00458  *
00459  * URI opener
00460  *
00461  */
00462 
00463 /**
00464  * Check validity of FTP control channel string
00465  *
00466  * @v string            String
00467  * @ret rc              Return status code
00468  */
00469 static int ftp_check_string ( const char *string ) {
00470         char c;
00471 
00472         /* The FTP control channel is line-based.  Check for invalid
00473          * non-printable characters (e.g. newlines).
00474          */
00475         while ( ( c = *(string++) ) ) {
00476                 if ( ! isprint ( c ) )
00477                         return -EINVAL;
00478         }
00479         return 0;
00480 }
00481 
00482 /**
00483  * Initiate an FTP connection
00484  *
00485  * @v xfer              Data transfer interface
00486  * @v uri               Uniform Resource Identifier
00487  * @ret rc              Return status code
00488  */
00489 static int ftp_open ( struct interface *xfer, struct uri *uri ) {
00490         struct ftp_request *ftp;
00491         struct sockaddr_tcpip server;
00492         int rc;
00493 
00494         /* Sanity checks */
00495         if ( ! uri->host )
00496                 return -EINVAL;
00497         if ( ! uri->path )
00498                 return -EINVAL;
00499         if ( ( rc = ftp_check_string ( uri->path ) ) != 0 )
00500                 return rc;
00501         if ( uri->user && ( ( rc = ftp_check_string ( uri->user ) ) != 0 ) )
00502                 return rc;
00503         if ( uri->password &&
00504              ( ( rc = ftp_check_string ( uri->password ) ) != 0 ) )
00505                 return rc;
00506 
00507         /* Allocate and populate structure */
00508         ftp = zalloc ( sizeof ( *ftp ) );
00509         if ( ! ftp )
00510                 return -ENOMEM;
00511         ref_init ( &ftp->refcnt, ftp_free );
00512         intf_init ( &ftp->xfer, &ftp_xfer_desc, &ftp->refcnt );
00513         intf_init ( &ftp->control, &ftp_control_desc, &ftp->refcnt );
00514         intf_init ( &ftp->data, &ftp_data_desc, &ftp->refcnt );
00515         ftp->uri = uri_get ( uri );
00516         ftp->recvbuf = ftp->status_text;
00517         ftp->recvsize = sizeof ( ftp->status_text ) - 1;
00518 
00519         DBGC ( ftp, "FTP %p fetching %s\n", ftp, ftp->uri->path );
00520 
00521         /* Open control connection */
00522         memset ( &server, 0, sizeof ( server ) );
00523         server.st_port = htons ( uri_port ( uri, FTP_PORT ) );
00524         if ( ( rc = xfer_open_named_socket ( &ftp->control, SOCK_STREAM,
00525                                              ( struct sockaddr * ) &server,
00526                                              uri->host, NULL ) ) != 0 )
00527                 goto err;
00528 
00529         /* Attach to parent interface, mortalise self, and return */
00530         intf_plug_plug ( &ftp->xfer, xfer );
00531         ref_put ( &ftp->refcnt );
00532         return 0;
00533 
00534  err:
00535         DBGC ( ftp, "FTP %p could not create request: %s\n", 
00536                ftp, strerror ( rc ) );
00537         ftp_done ( ftp, rc );
00538         ref_put ( &ftp->refcnt );
00539         return rc;
00540 }
00541 
00542 /** FTP URI opener */
00543 struct uri_opener ftp_uri_opener __uri_opener = {
00544         .scheme = "ftp",
00545         .open   = ftp_open,
00546 };