嵌入式 wget 参数解析篇

来源:互联网 发布:伴读软件 编辑:程序博客网 时间:2024/06/08 01:57

1 整体概括:

前提说明:

本篇wget分析仅仅是参数解析内容,不包括wget的递归和非递归下载,后面文章会陆续进行分析。本次主要分析参数为tries(t) timeout(T) no-clobber quiet(q) recursive(r) help(h)version(V) append-output(a) execute(e) no(n) clobber, 其中括号里面的为wget短选项,括号前面的为长选项。

 

在wget运行下载文件或页面时,用户可以通过参数来改变wget的行为,比如想查看wget的调试和http数据包可以使用 wget --debugwww.baidu.com/index.html。

 

我们这次分析下载url以baidu 搜索页面(http://www.baidu.com/index.html)为样本,进行分析不同类型的参数,以达到抛砖引玉的目的。wget支持长选项和短选项,比如输出调试信息短选项为-d长选项为—debug

 

wget有全局的struct options opt;保存着wget用户参数设置值,来修改wget行为。本篇主要讲解用户输入参数如何转化为 opt的成员。

 

wget分析的版本为1.13,gcc版本为3.4.5,linux内核版本2.6.9_5-9-0-0

2 详细代码解析:

2.1数据结构

wget 对于配置转化,设置struct options opt 有两张表和长短选项数组

命令行表:

struct cmdline_option option_data

此表保存着wget支持的长短选项和长短选项属性

命令转化设置opt表:

commands

此表用于设置根据参数来设置opt成员。

长选项:

struct option long_options[2*countof(option_data) + 1]

短选项:

struct char short_options[128]

2.2参数解析流程


Main 首先根据不同平台来设置使用时间函数,blog里有monotonic time和wall time讲解,这里就不分析。

2.2.1 defaults();

然后调用defaults函数,该函数主要是给全局opt设置默认值(因为代码太长,给出部分代码)。
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //#######################src/init.c  
  2. /* Reset the variables to default values.  */  
  3.   void  
  4.   defaults (void)  
  5.   {  
  6.     char *tmp;  
  7.     
  8.     /* Most of the default values are 0 (and 0.0, NULL, and false). 
  9.        Just reset everything, and fill in the non-zero values.  Note 
  10.        that initializing pointers to NULL this way is technically 
  11.        illegal, but porting Wget to a machine where NULL is not all-zero 
  12.        bit pattern will be the least of the implementors' worries.  */  
  13.     xzero (opt);  
  14.     
  15.     opt.cookies = true;  
  16.     opt.verbose = -1;  
  17.     opt.ntry = 20;  
  18.     opt.reclevel = 5;  
  19.     opt.add_hostdir = true;  
  20.     opt.netrc = true;  
  21.     opt.ftp_glob = true;  

2.2.2 init_switches()

函数很简单,追加一些ch注释

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static void  
  2.   init_switches (void)  
  3.   {  
  4.     //p指向短选项数组  
  5.     char *p = short_options;  
  6.     size_t i, o = 0;  
  7.     //遍历所有选项  
  8.     for (i = 0; i < countof (option_data); i++)  
  9.       {  
  10.         struct cmdline_option *opt = &option_data[i];  
  11.         struct option *longopt;  
  12.     
  13.         //如果这个选项数据没有长选项,直接跳过  
  14.         if (!opt->long_name)  
  15.           /* The option is disabled. */  
  16.           continue;  
  17.     
  18.         //longopt指向长选项一个依次节点  
  19.         longopt = &long_options[o++];  
  20.         //长选项name指向opt的long_name  
  21.         longopt->name = opt->long_name;  
  22.         //长选项val执行opt的数组索引,用于根据长选项查找opt  
  23.         longopt->val = i;  
  24.         if (opt->short_name)  
  25.          {  
  26.             //如果存在短选项,把opt short_name保存在short_options中  
  27.             *p++ = opt->short_name;  
  28.             //用optmap保存short_name的value 来索引长选项数组  
  29.             optmap[opt->short_name - 32] = longopt - long_options;  
  30.           }  
  31.         switch (opt->type)  
  32.           {  
  33.           case OPT_VALUE:  
  34.            //参数需要值  
  35.            longopt->has_arg = required_argument;  
  36.           //如果参数需要设置值,并且短选项存在,就需要字符":"  
  37.             if (opt->short_name)  
  38.               *p++ = ':';  
  39.             break;  
  40.           case OPT_BOOLEAN:  
  41.             /* 如果是bool类型(开关类型参数) 需要支持--option=off and --no-option .look the note of the blow*/  
  42.             /* Specify an optional argument for long options, so that 
  43.                --option=off works the same as --no-option, for 
  44.                compatibility with pre-1.10 Wget.  However, don't specify 
  45.                optional arguments short-option booleans because they 
  46.                prevent combining of short options.  */  
  47.             longopt->has_arg = optional_argument;  
  48.             /* For Boolean options, add the "--no-FOO" variant, which is 
  49.                identical to "--foo", except it has opposite meaning and 
  50.                it doesn't allow an argument.  */  
  51.             longopt = &long_options[o++];  
  52.             longopt->name = no_prefix (opt->long_name);  
  53.             longopt->has_arg = no_argument;  
  54.             /* Mask the value so we'll be able to recognize that we're 
  55.                dealing with the false value.  */  
  56.             //索引加一个负数符号  
  57.             longopt->val = i | BOOLEAN_NEG_MARKER;  
  58.             break;  
  59.           default:  
  60.             //others 根据情况设置不同的值  
  61.             assert (opt->argtype != -1);  
  62.             longopt->has_arg = opt->argtype;  
  63.             if (opt->short_name)  
  64.               {  
  65.                 if (longopt->has_arg == required_argument)  
  66.                   *p++ = ':';  
  67.                 /* Don't handle optional_argument */  
  68.               }  
  69.           }                                                                                                                                                           
  70.       }  
  71.     /* Terminate short_options. */  
  72.     *p = '\0';  
  73.     /* No need for xzero(long_options[o]) because its storage is static 
  74.        and it will be zeroed by default.  */  
  75.     assert (o <= countof (long_options));  
  76.   }  

举例分析(长选项为append-output ,短(a)):

用gdb跟踪下long_options和short_options

截取long_options一部分:


name(append-output) has_arg(1) val(2)

val==2 表示该长选项属性在option_data的索引


其中字符’a’ ascii值为97 那么这个在opt_map中索引为97-32=65

Such 


也就可以通过短选项找个长选项索引,然后这个长选项val就是option_data的数组索引。

2.2.1 main set opt

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. while ((ret = getopt_long (argc, argv,  
  2.                               short_options, long_options, &longindex)) != -1)  
  3.      {  
  4.        int val;  
  5.        struct cmdline_option *opt;  
  6.    
  7.        /* If LONGINDEX is unchanged, it means RET is referring a short 
  8.           option.  */  
  9.        if (longindex == -1)  
  10.          {  
  11.            if (ret == '?')  
  12.              {  
  13.                print_usage (0);  
  14.                printf ("\n");  
  15.                printf (_("Try `%s --help' for more options.\n"), exec_name);  
  16.                exit (2);  
  17.              }  
  18.            /* Find the short option character in the mapping.  */  
  19.            longindex = optmap[ret - 32];                                                                                                                             
  20.          }  
  21.        val = long_options[longindex].val;  
  22.    
  23.        /* Use the retrieved value to locate the option in the 
  24.           option_data array, and to see if we're dealing with the 
  25.           negated "--no-FOO" variant of the boolean option "--foo".  */  
  26.        opt = &option_data[val & ~BOOLEAN_NEG_MARKER];  

我截取了main处理argc argv部分代码。

调用过api getopt_long, 如果longindex==-1那么用户输入的是短选项,通过optmap来确定此短选项在长选项数组索引optmap[ret-32], 然后根据长选项的val找到在opt_data的此选项位置,如果用户输入的是长选项,就直接使用val。

val = long_options[longindex].val;

获取此选项opt_data

opt = &option_data[val &~BOOLEAN_NEG_MARKER];

 

找到了参数在opt_data的位置,然后下面就开始设置全局opt

根据参数类型分析以下参数:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. OPT_VALUE                   tries(t) timeout(T)   
  2. OPT_BOOLEAN             no-clobber quiet(q) recursive(r)  
  3. OPT_FUNCALL                 help(h) version(V)  
  4. OPT__APPEND_OUTPUT          append-output(a)  
  5. OPT_EXECUTE                 execute(e)  
  6. OPT_NO                      no(n)  
  7. OPT__PARENT|OPT__CLOBBER    clobber  

代码段:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. switch (opt->type)                                                                                                                                            
  2.    {  
  3.    case OPT_VALUE:  
  4.      setoptval (opt->data, optarg, opt->long_name);  
  5.      break;  
  6.    case OPT_BOOLEAN:  
  7.      if (optarg)  
  8.        /* The user has specified a value -- use it. */  
  9.        setoptval (opt->data, optarg, opt->long_name);  
  10.      else  
  11.        {  
  12.          /* NEG is true for `--no-FOO' style boolean options. */  
  13.          bool neg = !!(val & BOOLEAN_NEG_MARKER);  
  14.          setoptval (opt->data, neg ? "0" : "1", opt->long_name);  
  15.        }  
  16.      break;  
  17.    case OPT_FUNCALL:  
  18.      {  
  19.        void (*func) (void) = (void (*) (void)) opt->data;  
  20.        func ();  
  21.      }  
  22.      break;  
  23.    case OPT__APPEND_OUTPUT:  
  24.      setoptval ("logfile", optarg, opt->long_name);  
  25.      append_to_log = true;  
  26.      break;  
  27.    case OPT__EXECUTE:  
  28.      run_command (optarg);  
  29.      break;  
  30.    case OPT__NO:  
  31.      {  
  32.        /* We support real --no-FOO flags now, but keep these 
  33.           short options for convenience and backward 
  34.           compatibility.  */  
  35.        char *p;  
  36.        for (p = optarg; p && *p; p++)  
  37.          switch (*p)  
  38.            {  
  39.            case 'v':  
  40.              setoptval ("verbose""0", opt->long_name);  
  41.              break;  
  42.            case 'H':  
  43.              setoptval ("addhostdir""0", opt->long_name);  
  44.              break;  
  45.            case 'd':  
  46.              setoptval ("dirstruct""0", opt->long_name);  
  47.              break;  
  48.            case 'c':  
  49.              setoptval ("noclobber""1", opt->long_name);  
  50.              break;  
  51.            case 'p':  
  52.              setoptval ("noparent""1", opt->long_name);  
  53.              break;  
  54.            default:  
  55.              fprintf (stderr, _("%s: illegal option -- `-n%c'\n"),  
  56.                       exec_name, *p);  
  57.              print_usage (1);  
  58.              fprintf (stderr, "\n");  
  59.              fprintf (stderr, _("Try `%s --help' for more options.\n"),                                                                                        
  60.                       exec_name);  
  61.              exit (1);  
  62.            }  
  63.        break;  
  64.      }  
  65.    case OPT__PARENT:  
  66.    case OPT__CLOBBER:  
  67.    case OPT__CLOBBER:  
  68.      {  
  69.        /* The wgetrc commands are named noparent and noclobber, 
  70.           so we must revert the meaning of the cmdline options 
  71.           before passing the value to setoptval.  */  
  72.        bool flag = true;  
  73.        if (optarg)  
  74.          flag = (*optarg == '1' || c_tolower (*optarg) == 'y'  
  75.                  || (c_tolower (optarg[0]) == 'o'  
  76.                      && c_tolower (optarg[1]) == 'n'));  
  77.        setoptval (opt->type == OPT__PARENT ? "noparent" : "noclobber",  
  78.                   flag ? "0" : "1", opt->long_name);  
  79.        break;  
  80.      }  
  81.    case OPT__DONT_REMOVE_LISTING:  
  82.      setoptval ("removelisting""0", opt->long_name);  
  83.      break;  
  84.    }  
  85.   
  86.  longindex = -1;  

参数类型OPT_VALUE(t,T)

Setoptval(opt->data, optarg,opt->long_name)

         ->setval_internal(command_by_name(opt->data),“--“+opt->long_name, optarg)

其中command_by_name(opt->data)是通过二分查找,找到data在commands中的索引位置

Code:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static int  
  2. command_by_name (const char *cmdname)  
  3. {  
  4.   /* Use binary search for speed.  Wget has ~100 commands, which 
  5.      guarantees a worst case performance of 7 string comparisons.  */  
  6.   int lo = 0, hi = countof (commands) - 1;                                                                                                                          
  7.   
  8.   while (lo <= hi)  
  9.     {  
  10.       int mid = (lo + hi) >> 1;  
  11.       int cmp = strcasecmp (cmdname, commands[mid].name);  
  12.       if (cmp < 0)  
  13.         hi = mid - 1;  
  14.       else if (cmp > 0)  
  15.         lo = mid + 1;  
  16.       else  
  17.         return mid;  
  18.     }  
  19.   return -1;  
  20. }  

set_internal(comind, “--“+opt->long_name,optarg)

         ->commands[comind].action (“--“+opt->long_name, optarg,commands[comind].place);

比如tries commands信息如下

{ "tries",            &opt.ntry,              cmd_number_inf },

调用cmd_num_inf(“—tries”, optarg, opt.ntry)

函数设置opt.ntry = strtoul(optarg, 10,. NULL)

参数类型OPT_BOOLEAN

和OPT_BOOLEAN大同小异,此处略过。

参数类型OPT_FUNCALL

-h 和 –v

调用opt->data

如果用户输入参数为-h或者-v就会调用print_help or print_version,这里就略过了。

参数类型OPT__APPEND_OUTPUT

setoptval ("logfile", optarg,opt->long_name);//和OPT_VALUE相似,略过。

参数类型OPT__EXECUTE

参数-e

Run_command(optarg)

其中optarg 格式为key=value,此函数解析出key和value,比如append-output=logfile.txt

就会调用set_internal(comind, com, val)来设置opt

参数类型OPT__NO、OPT__PARENT、OPT__CLOBBER、OPT__DONT_REMOVE_LISTING都是大同小异,这里就略过了。

 

0 0
原创粉丝点击