4.1 種子解析模組的設計和實現
解析種子檔案主要在parse_metafile.h和parse_metafile.c中完成。parse_metafile.h檔案的內容為:
parse_metafile.h
#ifndef PARSE_METAFILE
#define PARSE_METAFILE
// 儲存從種子檔案中擷取的tracker的URL
typedef struct _Announce_list {
char announce[128];
struct _Announce_list *next;
} Announce_list;
// 儲存各個待下載檔案的路徑和長度
typedef struct _Files {
char path[256];
long length;
struct _Files *next;
} Files;
int read_metafile(char *metafile_name); // 讀取種子檔案
int find_keyword(char *keyword,long *position); // 在種子檔案中尋找某個關鍵詞
int read_announce_list(); // 擷取各個tracker伺服器的地址
int add_an_announce(char* url); // 向tracker列表添加一個URL
int get_piece_length(); // 擷取每個piece的長度,一般為256KB
int get_pieces(); // 讀取各個piece的雜湊值
int is_multi_files(); // 判斷下載的是單個檔案還是多個檔案
int get_file_name(); // 擷取檔案名稱,對於多檔案,擷取的是目錄名
int get_file_length(); // 擷取待下載檔案的總長度
int get_files_length_path(); // 擷取檔案的路徑和長度,對多檔案種子有效
int get_info_hash(); // 由info關鍵詞對應的值計算info_hash
int get_peer_id(); // 產生peer_id,每個peer都有一個20位元組的peer_id
void release_memory_in_parse_metafile();// 釋放parse_metafile.c中動態分配的記憶體
int parse_metafile(char *metafile); // 調用本檔案中定義的函數,完成解析種子檔案
#endif
以下是parse_metafile.c檔案的頭部,主要是包含了一些標頭檔和定義一些全域變數,各個函數的定義將在後面列出。
parse_metafile.c
#include <stdio.h>
#include <ctype.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "parse_metafile.h"
#include "sha1.h"
char *metafile_content = NULL; // 儲存種子檔案的內容
long filesize; // 種子檔案的長度
int piece_length = 0; // 每個piece的長度,通常為256KB即262144位元組