File: protocol.c

package info (click to toggle)
apt-spy 3.1-16
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 312 kB
  • ctags: 55
  • sloc: ansic: 826; makefile: 53; sh: 6
file content (97 lines) | stat: -rw-r--r-- 2,381 bytes parent folder | download | duplicates (2)
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
/* 
 * apt-spy (c) Steven Holmes, 2003. 
 * This software is licensed as detailed in the COPYRIGHT file
 */

#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <curl/curl.h>

#include "include/parse.h"
#include "include/protocols.h"

int get_file(server_t *current, CURL *curl, char *file, enum protocol protocol, size_t *total_bytes)
{
	char errorbuff[CURL_ERROR_SIZE + 1];
	int urlsize=0;
	char *url;
	double download_speed;
	double download_time;
	int error;

	/* Reset byte counter */
	*total_bytes = 0;
	
	/* Give us human readable error messages in errorbuff */
	if (curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorbuff) != 0)
		return 1;

	assert(HTTP==protocol || FTP==protocol);
	urlsize=8+strlen(current->hostname)+strlen(current->path[protocol])+strlen(file);
	url=malloc(urlsize);
	if (!url) {
		perror("malloc");
		exit(1);
	}

	if (HTTP==protocol)	strcpy(url, "http://");
	else if (FTP==protocol)	strcpy(url, "ftp://");
	
	strcat(url, current->hostname);

	/* Complete the URL. Also save it for later use when writing sources.list */
	if (protocol == HTTP) {
		strcat(url, current->path[HTTP]);
		current->url[HTTP]=strdup(url);
	} else {
		strcat(url, current->path[FTP]);
		current->url[FTP]=strdup(url);
	}

	strcat(url, file);
	
	/* And register it */
	if (curl_easy_setopt(curl, CURLOPT_URL, url) != 0) {
		free(url);
		return 1;
	}
	
	/* Now do the actual transfer */
	error = curl_easy_perform(curl);
	if (error != 0) {
		if (error != CURLE_OPERATION_TIMEDOUT) {
			free(url);
			fprintf(stderr, "\t\tError: %s\n", errorbuff);
			return 1;
		} else if (*total_bytes == 0) {
			free(url);
			fprintf(stderr, "\t\tError: %s\n", errorbuff);
			return 1;
		}			
	}
	
	/* And get the statistics and store them */
	curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &download_time);

	if (*total_bytes == 0) {
		fprintf(stderr, "\t\tNo data was transfered\n");
		free(url);
		return 1;
	}
	                                                
	printf("\t\tDownloaded %i bytes in %2.2f seconds\n", *total_bytes, download_time);

	/* Calculate download speed... */
	download_speed = (double) (*total_bytes) / download_time;

	printf("\t\tDownload speed: %.2f kB/sec\n", download_speed / (double) 1024);

	if (download_speed > current->stats.speed) {
		current->stats.speed = download_speed;
		current->stats.protocol = protocol;
	}	

	free(url);
	return 0;
}