summaryrefslogtreecommitdiffstats
path: root/qemu/roms/ipxe/src/net/tcp/ftp.c
blob: be7a7c3b54abbd3b1f7e05871e24ac9cf5d2b904 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/*
 * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <ctype.h>
#include <byteswap.h>
#include <ipxe/socket.h>
#include <ipxe/tcpip.h>
#include <ipxe/in.h>
#include <ipxe/iobuf.h>
#include <ipxe/xfer.h>
#include <ipxe/open.h>
#include <ipxe/uri.h>
#include <ipxe/features.h>
#include <ipxe/ftp.h>

/** @file
 *
 * File transfer protocol
 *
 */

FEATURE ( FEATURE_PROTOCOL, "FTP", DHCP_EB_FEATURE_FTP, 1 );

/**
 * FTP states
 *
 * These @b must be sequential, i.e. a successful FTP session must
 * pass through each of these states in order.
 */
enum ftp_state {
	FTP_CONNECT = 0,
	FTP_USER,
	FTP_PASS,
	FTP_TYPE,
	FTP_SIZE,
	FTP_PASV,
	FTP_RETR,
	FTP_WAIT,
	FTP_QUIT,
	FTP_DONE,
};

/**
 * An FTP request
 *
 */
struct ftp_request {
	/** Reference counter */
	struct refcnt refcnt;
	/** Data transfer interface */
	struct interface xfer;

	/** URI being fetched */
	struct uri *uri;
	/** FTP control channel interface */
	struct interface control;
	/** FTP data channel interface */
	struct interface data;

	/** Current state */
	enum ftp_state state;
	/** Buffer to be filled with data received via the control channel */
	char *recvbuf;
	/** Remaining size of recvbuf */
	size_t recvsize;
	/** FTP status code, as text */
	char status_text[5];
	/** Passive-mode parameters, as text */
	char passive_text[24]; /* "aaa,bbb,ccc,ddd,eee,fff" */
	/** File size, as text */
	char filesize[20];
};

/**
 * Free FTP request
 *
 * @v refcnt		Reference counter
 */
static void ftp_free ( struct refcnt *refcnt ) {
	struct ftp_request *ftp =
		container_of ( refcnt, struct ftp_request, refcnt );

	DBGC ( ftp, "FTP %p freed\n", ftp );

	uri_put ( ftp->uri );
	free ( ftp );
}

/**
 * Mark FTP operation as complete
 *
 * @v ftp		FTP request
 * @v rc		Return status code
 */
static void ftp_done ( struct ftp_request *ftp, int rc ) {

	DBGC ( ftp, "FTP %p completed (%s)\n", ftp, strerror ( rc ) );

	/* Close all data transfer interfaces */
	intf_shutdown ( &ftp->data, rc );
	intf_shutdown ( &ftp->control, rc );
	intf_shutdown ( &ftp->xfer, rc );
}

/*****************************************************************************
 *
 * FTP control channel
 *
 */

/** An FTP control channel string */
struct ftp_control_string {
	/** Literal portion */
	const char *literal;
	/** Variable portion
	 *
	 * @v ftp	FTP request
	 * @ret string	Variable portion of string
	 */
	const char * ( *variable ) ( struct ftp_request *ftp );
};

/**
 * Retrieve FTP pathname
 *
 * @v ftp		FTP request
 * @ret path		FTP pathname
 */
static const char * ftp_uri_path ( struct ftp_request *ftp ) {
	return ftp->uri->path;
}

/**
 * Retrieve FTP user
 *
 * @v ftp		FTP request
 * @ret user		FTP user
 */
static const char * ftp_user ( struct ftp_request *ftp ) {
	static char *ftp_default_user = "anonymous";
	return ftp->uri->user ? ftp->uri->user : ftp_default_user;
}

/**
 * Retrieve FTP password
 *
 * @v ftp		FTP request
 * @ret password	FTP password
 */
static const char * ftp_password ( struct ftp_request *ftp ) {
	static char *ftp_default_password = "ipxe@ipxe.org";
	return ftp->uri->password ? ftp->uri->password : ftp_default_password;
}

/** FTP control channel strings */
static struct ftp_control_string ftp_strings[] = {
	[FTP_CONNECT]	= { NULL, NULL },
	[FTP_USER]	= { "USER ", ftp_user },
	[FTP_PASS]	= { "PASS ", ftp_password },
	[FTP_TYPE]	= { "TYPE I", NULL },
	[FTP_SIZE]	= { "SIZE ", ftp_uri_path },
	[FTP_PASV]	= { "PASV", NULL },
	[FTP_RETR]	= { "RETR ", ftp_uri_path },
	[FTP_WAIT]	= { NULL, NULL },
	[FTP_QUIT]	= { "QUIT", NULL },
	[FTP_DONE]	= { NULL, NULL },
};

/**
 * Parse FTP byte sequence value
 *
 * @v text		Text string
 * @v value		Value buffer
 * @v len		Length of value buffer
 *
 * This parses an FTP byte sequence value (e.g. the "aaa,bbb,ccc,ddd"
 * form for IP addresses in PORT commands) into a byte sequence.  @c
 * *text will be updated to point beyond the end of the parsed byte
 * sequence.
 *
 * This function is safe in the presence of malformed data, though the
 * output is undefined.
 */
static void ftp_parse_value ( char **text, uint8_t *value, size_t len ) {
	do {
		*(value++) = strtoul ( *text, text, 10 );
		if ( **text )
			(*text)++;
	} while ( --len );
}

/**
 * Move to next state and send the appropriate FTP control string
 *
 * @v ftp		FTP request
 *
 */
static void ftp_next_state ( struct ftp_request *ftp ) {
	struct ftp_control_string *ftp_string;
	const char *literal;
	const char *variable;

	/* Move to next state */
	if ( ftp->state < FTP_DONE )
		ftp->state++;

	/* Send control string if needed */
	ftp_string = &ftp_strings[ftp->state];
	literal = ftp_string->literal;
	variable = ( ftp_string->variable ?
		     ftp_string->variable ( ftp ) : "" );
	if ( literal ) {
		DBGC ( ftp, "FTP %p sending %s%s\n", ftp, literal, variable );
		xfer_printf ( &ftp->control, "%s%s\r\n", literal, variable );
	}
}

/**
 * Handle an FTP control channel response
 *
 * @v ftp		FTP request
 *
 * This is called once we have received a complete response line.
 */
static void ftp_reply ( struct ftp_request *ftp ) {
	char status_major = ftp->status_text[0];
	char separator = ftp->status_text[3];

	DBGC ( ftp, "FTP %p received status %s\n", ftp, ftp->status_text );

	/* Ignore malformed lines */
	if ( separator != ' ' )
		return;

	/* Ignore "intermediate" responses (1xx codes) */
	if ( status_major == '1' )
		return;

	/* If the SIZE command is not supported by the server, we go to
	 * the next step.
	 */
	if ( ( status_major == '5' ) && ( ftp->state == FTP_SIZE ) ) {
		ftp_next_state ( ftp );
		return;
	}

	/* Anything other than success (2xx) or, in the case of a
	 * repsonse to a "USER" command, a password prompt (3xx), is a
	 * fatal error.
	 */
	if ( ! ( ( status_major == '2' ) ||
		 ( ( status_major == '3' ) && ( ftp->state == FTP_USER ) ) ) ){
		/* Flag protocol error and close connections */
		ftp_done ( ftp, -EPROTO );
		return;
	}

	/* Parse file size */
	if ( ftp->state == FTP_SIZE ) {
		size_t filesize;
		char *endptr;

		/* Parse size */
		filesize = strtoul ( ftp->filesize, &endptr, 10 );
		if ( *endptr != '\0' ) {
			DBGC ( ftp, "FTP %p invalid SIZE \"%s\"\n",
			       ftp, ftp->filesize );
			ftp_done ( ftp, -EPROTO );
			return;
		}

		/* Use seek() to notify recipient of filesize */
		DBGC ( ftp, "FTP %p file size is %zd bytes\n", ftp, filesize );
		xfer_seek ( &ftp->xfer, filesize );
		xfer_seek ( &ftp->xfer, 0 );
	}

	/* Open passive connection when we get "PASV" response */
	if ( ftp->state == FTP_PASV ) {
		char *ptr = ftp->passive_text;
		union {
			struct sockaddr_in sin;
			struct sockaddr sa;
		} sa;
		int rc;

		sa.sin.sin_family = AF_INET;
		ftp_parse_value ( &ptr, ( uint8_t * ) &sa.sin.sin_addr,
				  sizeof ( sa.sin.sin_addr ) );
		ftp_parse_value ( &ptr, ( uint8_t * ) &sa.sin.sin_port,
				  sizeof ( sa.sin.sin_port ) );
		if ( ( rc = xfer_open_socket ( &ftp->data, SOCK_STREAM,
					       &sa.sa, NULL ) ) != 0 ) {
			DBGC ( ftp, "FTP %p could not open data connection\n",
			       ftp );
			ftp_done ( ftp, rc );
			return;
		}
	}

	/* Move to next state and send control string */
	ftp_next_state ( ftp );
	
}

/**
 * Handle new data arriving on FTP control channel
 *
 * @v ftp		FTP request
 * @v iob		I/O buffer
 * @v meta		Data transfer metadata
 * @ret rc		Return status code
 *
 * Data is collected until a complete line is received, at which point
 * its information is passed to ftp_reply().
 */
static int ftp_control_deliver ( struct ftp_request *ftp,
				 struct io_buffer *iobuf,
				 struct xfer_metadata *meta __unused ) {
	char *data = iobuf->data;
	size_t len = iob_len ( iobuf );
	char *recvbuf = ftp->recvbuf;
	size_t recvsize = ftp->recvsize;
	char c;
	
	while ( len-- ) {
		c = *(data++);
		if ( ( c == '\r' ) || ( c == '\n' ) ) {
			/* End of line: call ftp_reply() to handle
			 * completed reply.  Avoid calling ftp_reply()
			 * twice if we receive both \r and \n.
			 */
			if ( recvbuf != ftp->status_text )
				ftp_reply ( ftp );
			/* Start filling up the status code buffer */
			recvbuf = ftp->status_text;
			recvsize = sizeof ( ftp->status_text ) - 1;
		} else if ( ( ftp->state == FTP_PASV ) && ( c == '(' ) ) {
			/* Start filling up the passive parameter buffer */
			recvbuf = ftp->passive_text;
			recvsize = sizeof ( ftp->passive_text ) - 1;
		} else if ( ( ftp->state == FTP_PASV ) && ( c == ')' ) ) {
			/* Stop filling the passive parameter buffer */
			recvsize = 0;
		} else if ( ( ftp->state == FTP_SIZE ) && ( c == ' ' ) ) {
			/* Start filling up the file size buffer */
			recvbuf = ftp->filesize;
			recvsize = sizeof ( ftp->filesize ) - 1;
		} else {
			/* Fill up buffer if applicable */
			if ( recvsize > 0 ) {
				*(recvbuf++) = c;
				recvsize--;
			}
		}
	}

	/* Store for next invocation */
	ftp->recvbuf = recvbuf;
	ftp->recvsize = recvsize;

	/* Free I/O buffer */
	free_iob ( iobuf );

	return 0;
}

/** FTP control channel interface operations */
static struct interface_operation ftp_control_operations[] = {
	INTF_OP ( xfer_deliver, struct ftp_request *, ftp_control_deliver ),
	INTF_OP ( intf_close, struct ftp_request *, ftp_done ),
};

/** FTP control channel interface descriptor */
static struct interface_descriptor ftp_control_desc =
	INTF_DESC ( struct ftp_request, control, ftp_control_operations );

/*****************************************************************************
 *
 * FTP data channel
 *
 */

/**
 * Handle FTP data channel being closed
 *
 * @v ftp		FTP request
 * @v rc		Reason for closure
 *
 * When the data channel is closed, the control channel should be left
 * alone; the server will send a completion message via the control
 * channel which we'll pick up.
 *
 * If the data channel is closed due to an error, we abort the request.
 */
static void ftp_data_closed ( struct ftp_request *ftp, int rc ) {

	DBGC ( ftp, "FTP %p data connection closed: %s\n",
	       ftp, strerror ( rc ) );
	
	/* If there was an error, close control channel and record status */
	if ( rc ) {
		ftp_done ( ftp, rc );
	} else {
		ftp_next_state ( ftp );
	}
}

/** FTP data channel interface operations */
static struct interface_operation ftp_data_operations[] = {
	INTF_OP ( intf_close, struct ftp_request *, ftp_data_closed ),
};

/** FTP data channel interface descriptor */
static struct interface_descriptor ftp_data_desc =
	INTF_DESC_PASSTHRU ( struct ftp_request, data, ftp_data_operations,
			     xfer );

/*****************************************************************************
 *
 * Data transfer interface
 *
 */

/** FTP data transfer interface operations */
static struct interface_operation ftp_xfer_operations[] = {
	INTF_OP ( intf_close, struct ftp_request *, ftp_done ),
};

/** FTP data transfer interface descriptor */
static struct interface_descriptor ftp_xfer_desc =
	INTF_DESC_PASSTHRU ( struct ftp_request, xfer, ftp_xfer_operations,
			     data );

/*****************************************************************************
 *
 * URI opener
 *
 */

/**
 * Check validity of FTP control channel string
 *
 * @v string		String
 * @ret rc		Return status code
 */
static int ftp_check_string ( const char *string ) {
	char c;

	/* The FTP control channel is line-based.  Check for invalid
	 * non-printable characters (e.g. newlines).
	 */
	while ( ( c = *(string++) ) ) {
		if ( ! isprint ( c ) )
			return -EINVAL;
	}
	return 0;
}

/**
 * Initiate an FTP connection
 *
 * @v xfer		Data transfer interface
 * @v uri		Uniform Resource Identifier
 * @ret rc		Return status code
 */
static int ftp_open ( struct interface *xfer, struct uri *uri ) {
	struct ftp_request *ftp;
	struct sockaddr_tcpip server;
	int rc;

	/* Sanity checks */
	if ( ! uri->host )
		return -EINVAL;
	if ( ! uri->path )
		return -EINVAL;
	if ( ( rc = ftp_check_string ( uri->path ) ) != 0 )
		return rc;
	if ( uri->user && ( ( rc = ftp_check_string ( uri->user ) ) != 0 ) )
		return rc;
	if ( uri->password &&
	     ( ( rc = ftp_check_string ( uri->password ) ) != 0 ) )
		return rc;

	/* Allocate and populate structure */
	ftp = zalloc ( sizeof ( *ftp ) );
	if ( ! ftp )
		return -ENOMEM;
	ref_init ( &ftp->refcnt, ftp_free );
	intf_init ( &ftp->xfer, &ftp_xfer_desc, &ftp->refcnt );
	intf_init ( &ftp->control, &ftp_control_desc, &ftp->refcnt );
	intf_init ( &ftp->data, &ftp_data_desc, &ftp->refcnt );
	ftp->uri = uri_get ( uri );
	ftp->recvbuf = ftp->status_text;
	ftp->recvsize = sizeof ( ftp->status_text ) - 1;

	DBGC ( ftp, "FTP %p fetching %s\n", ftp, ftp->uri->path );

	/* Open control connection */
	memset ( &server, 0, sizeof ( server ) );
	server.st_port = htons ( uri_port ( uri, FTP_PORT ) );
	if ( ( rc = xfer_open_named_socket ( &ftp->control, SOCK_STREAM,
					     ( struct sockaddr * ) &server,
					     uri->host, NULL ) ) != 0 )
		goto err;

	/* Attach to parent interface, mortalise self, and return */
	intf_plug_plug ( &ftp->xfer, xfer );
	ref_put ( &ftp->refcnt );
	return 0;

 err:
	DBGC ( ftp, "FTP %p could not create request: %s\n", 
	       ftp, strerror ( rc ) );
	ftp_done ( ftp, rc );
	ref_put ( &ftp->refcnt );
	return rc;
}

/** FTP URI opener */
struct uri_opener ftp_uri_opener __uri_opener = {
	.scheme	= "ftp",
	.open	= ftp_open,
};