Main文件是Tor系统的主要执行函数所处文件,内容偏多,但是较于其他底层处理函数所在的文件,也算较少。所以这里做简要的分析,其中删去很多不常见的,不重要的函数,大家可以自行在源文件内部查看。
1. 全局变量
全局变量在文件头部定义,每个全局变量都已经有比较详尽的英文分析和解释,这里再做简单的罗列。
1)系统(先前)已读与已写字节数以及用于流量控制的令牌桶全局变量;(先前与当前已读写字节数的区别与refill回调函数相关)
令牌桶用于控制整个系统的流量,经过初始化,减少,增加等操作(当读写相应的令牌数不够时,系统或连接会停止读或写):
// 初始化令牌桶令牌数
/** Initialize the global read bucket to options-\>BandwidthBurst. */
void
connection_bucket_init(void)
{
const or_options_t *options = get_options();
/* start it at max traffic */
global_read_bucket = (int)options->BandwidthBurst;
global_write_bucket = (int)options->BandwidthBurst;
if (options->RelayBandwidthRate) {
global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
} else {
global_relayed_read_bucket = (int)options->BandwidthBurst;
global_relayed_write_bucket = (int)options->BandwidthBurst;
}
}
// 减少令牌桶令牌数
/** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
* onto <b>conn</b>. Decrement buckets appropriately. */
static void
connection_buckets_decrement(connection_t *conn, time_t now,
size_t num_read, size_t num_written)
{
......
if (connection_counts_as_relayed_traffic(conn, now)) {
global_relayed_read_bucket -= (int)num_read;
global_relayed_write_bucket -= (int)num_written;
}
global_read_bucket -= (int)num_read;
global_write_bucket -= (int)num_written;
......
}
// 增加令牌桶令牌数
/** Time has passed; increment buckets appropriately. */
void
connection_bucket_refill(int milliseconds_elapsed, time_t now)
{
......
/* refill the global buckets */
connection_bucket_refill_helper(&global_read_bucket,
bandwidthrate, bandwidthburst,
milliseconds_elapsed,
"global_read_bucket");
conn