cmndline.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: cmndline.cc,v 1.15 2003/02/10 01:40:58 doogie Exp $
  4. /* ######################################################################
  5. Command Line Class - Sophisticated command line parser
  6. This source is placed in the Public Domain, do with it what you will
  7. It was originally written by Jason Gunthorpe <jgg@debian.org>.
  8. ##################################################################### */
  9. /*}}}*/
  10. // Include files /*{{{*/
  11. #include<config.h>
  12. #include <apt-pkg/configuration.h>
  13. #include <apt-pkg/cmndline.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/strutl.h>
  16. #include <stddef.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <string>
  20. #include <apti18n.h>
  21. /*}}}*/
  22. using namespace std;
  23. // CommandLine::CommandLine - Constructor /*{{{*/
  24. // ---------------------------------------------------------------------
  25. /* */
  26. CommandLine::CommandLine(Args *AList,Configuration *Conf) : ArgList(AList),
  27. Conf(Conf), FileList(0)
  28. {
  29. }
  30. /*}}}*/
  31. // CommandLine::~CommandLine - Destructor /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* */
  34. CommandLine::~CommandLine()
  35. {
  36. delete [] FileList;
  37. }
  38. /*}}}*/
  39. // CommandLine::GetCommand - return the first non-option word /*{{{*/
  40. char const * CommandLine::GetCommand(Dispatch const * const Map,
  41. unsigned int const argc, char const * const * const argv)
  42. {
  43. // if there is a -- on the line there must be the word we search for around it
  44. // as -- marks the end of the options, just not sure if the command can be
  45. // considered an option or not, so accept both
  46. for (size_t i = 1; i < argc; ++i)
  47. {
  48. if (strcmp(argv[i], "--") != 0)
  49. continue;
  50. ++i;
  51. if (i < argc)
  52. for (size_t j = 0; Map[j].Match != NULL; ++j)
  53. if (strcmp(argv[i], Map[j].Match) == 0)
  54. return Map[j].Match;
  55. i -= 2;
  56. if (i != 0)
  57. for (size_t j = 0; Map[j].Match != NULL; ++j)
  58. if (strcmp(argv[i], Map[j].Match) == 0)
  59. return Map[j].Match;
  60. return NULL;
  61. }
  62. // no --, so search for the first word matching a command
  63. // FIXME: How like is it that an option parameter will be also a valid Match ?
  64. for (size_t i = 1; i < argc; ++i)
  65. {
  66. if (*(argv[i]) == '-')
  67. continue;
  68. for (size_t j = 0; Map[j].Match != NULL; ++j)
  69. if (strcmp(argv[i], Map[j].Match) == 0)
  70. return Map[j].Match;
  71. }
  72. return NULL;
  73. }
  74. /*}}}*/
  75. // CommandLine::Parse - Main action member /*{{{*/
  76. // ---------------------------------------------------------------------
  77. /* */
  78. bool CommandLine::Parse(int argc,const char **argv)
  79. {
  80. delete [] FileList;
  81. FileList = new const char *[argc];
  82. const char **Files = FileList;
  83. int I;
  84. for (I = 1; I != argc; I++)
  85. {
  86. const char *Opt = argv[I];
  87. // It is not an option
  88. if (*Opt != '-')
  89. {
  90. *Files++ = Opt;
  91. continue;
  92. }
  93. Opt++;
  94. // Double dash signifies the end of option processing
  95. if (*Opt == '-' && Opt[1] == 0)
  96. {
  97. I++;
  98. break;
  99. }
  100. // Single dash is a short option
  101. if (*Opt != '-')
  102. {
  103. // Iterate over each letter
  104. while (*Opt != 0)
  105. {
  106. // Search for the option
  107. Args *A;
  108. for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
  109. if (A->end() == true)
  110. return _error->Error(_("Command line option '%c' [from %s] is not known."),*Opt,argv[I]);
  111. if (HandleOpt(I,argc,argv,Opt,A) == false)
  112. return false;
  113. if (*Opt != 0)
  114. Opt++;
  115. }
  116. continue;
  117. }
  118. Opt++;
  119. // Match up to a = against the list
  120. Args *A;
  121. const char *OptEnd = strchrnul(Opt, '=');
  122. for (A = ArgList; A->end() == false &&
  123. (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
  124. ++A);
  125. // Failed, look for a word after the first - (no-foo)
  126. bool PreceedMatch = false;
  127. if (A->end() == true)
  128. {
  129. Opt = (const char*) memchr(Opt, '-', OptEnd - Opt);
  130. if (Opt == NULL)
  131. return _error->Error(_("Command line option %s is not understood"),argv[I]);
  132. Opt++;
  133. for (A = ArgList; A->end() == false &&
  134. (A->LongOpt == 0 || stringcasecmp(Opt,OptEnd,A->LongOpt) != 0);
  135. ++A);
  136. // Failed again..
  137. if (A->end() == true && OptEnd - Opt != 1)
  138. return _error->Error(_("Command line option %s is not understood"),argv[I]);
  139. // The option could be a single letter option prefixed by a no-..
  140. if (A->end() == true)
  141. {
  142. for (A = ArgList; A->end() == false && A->ShortOpt != *Opt; A++);
  143. if (A->end() == true)
  144. return _error->Error(_("Command line option %s is not understood"),argv[I]);
  145. }
  146. // The option is not boolean
  147. if (A->IsBoolean() == false)
  148. return _error->Error(_("Command line option %s is not boolean"),argv[I]);
  149. PreceedMatch = true;
  150. }
  151. // Deal with it.
  152. OptEnd--;
  153. if (HandleOpt(I,argc,argv,OptEnd,A,PreceedMatch) == false)
  154. return false;
  155. }
  156. // Copy any remaining file names over
  157. for (; I != argc; I++)
  158. *Files++ = argv[I];
  159. *Files = 0;
  160. SaveInConfig(argc, argv);
  161. return true;
  162. }
  163. /*}}}*/
  164. // CommandLine::HandleOpt - Handle a single option including all flags /*{{{*/
  165. // ---------------------------------------------------------------------
  166. /* This is a helper function for parser, it looks at a given argument
  167. and looks for specific patterns in the string, it gets tokanized
  168. -ruffly- like -*[yes|true|enable]-(o|longopt)[=][ ][argument] */
  169. bool CommandLine::HandleOpt(int &I,int argc,const char *argv[],
  170. const char *&Opt,Args *A,bool PreceedMatch)
  171. {
  172. const char *Argument = 0;
  173. bool CertainArg = false;
  174. int IncI = 0;
  175. /* Determine the possible location of an option or 0 if their is
  176. no option */
  177. if (Opt[1] == 0 || (Opt[1] == '=' && Opt[2] == 0))
  178. {
  179. if (I + 1 < argc && argv[I+1][0] != '-')
  180. Argument = argv[I+1];
  181. // Equals was specified but we fell off the end!
  182. if (Opt[1] == '=' && Argument == 0)
  183. return _error->Error(_("Option %s requires an argument."),argv[I]);
  184. if (Opt[1] == '=')
  185. CertainArg = true;
  186. IncI = 1;
  187. }
  188. else
  189. {
  190. if (Opt[1] == '=')
  191. {
  192. CertainArg = true;
  193. Argument = Opt + 2;
  194. }
  195. else
  196. Argument = Opt + 1;
  197. }
  198. // Option is an argument set
  199. if ((A->Flags & HasArg) == HasArg)
  200. {
  201. if (Argument == 0)
  202. return _error->Error(_("Option %s requires an argument."),argv[I]);
  203. Opt += strlen(Opt);
  204. I += IncI;
  205. // Parse a configuration file
  206. if ((A->Flags & ConfigFile) == ConfigFile)
  207. return ReadConfigFile(*Conf,Argument);
  208. // Arbitrary item specification
  209. if ((A->Flags & ArbItem) == ArbItem)
  210. {
  211. const char *J = strchr(Argument, '=');
  212. if (J == NULL)
  213. return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
  214. // = is trailing
  215. if (J[1] == 0)
  216. {
  217. if (I+1 >= argc)
  218. return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
  219. Conf->Set(string(Argument,J-Argument),string(argv[I++ +1]));
  220. }
  221. else
  222. Conf->Set(string(Argument,J-Argument),string(J+1));
  223. return true;
  224. }
  225. const char *I = strchrnul(A->ConfName, ' ');
  226. if (*I == ' ')
  227. Conf->Set(string(A->ConfName,0,I-A->ConfName),string(I+1) + Argument);
  228. else
  229. Conf->Set(A->ConfName,string(I) + Argument);
  230. return true;
  231. }
  232. // Option is an integer level
  233. if ((A->Flags & IntLevel) == IntLevel)
  234. {
  235. // There might be an argument
  236. if (Argument != 0)
  237. {
  238. char *EndPtr;
  239. unsigned long Value = strtol(Argument,&EndPtr,10);
  240. // Conversion failed and the argument was specified with an =s
  241. if (EndPtr == Argument && CertainArg == true)
  242. return _error->Error(_("Option %s requires an integer argument, not '%s'"),argv[I],Argument);
  243. // Conversion was ok, set the value and return
  244. if (EndPtr != 0 && EndPtr != Argument && *EndPtr == 0)
  245. {
  246. Conf->Set(A->ConfName,Value);
  247. Opt += strlen(Opt);
  248. I += IncI;
  249. return true;
  250. }
  251. }
  252. // Increase the level
  253. Conf->Set(A->ConfName,Conf->FindI(A->ConfName)+1);
  254. return true;
  255. }
  256. // Option is a boolean
  257. int Sense = -1; // -1 is unspecified, 0 is yes 1 is no
  258. // Look for an argument.
  259. while (1)
  260. {
  261. // Look at preceding text
  262. char Buffer[300];
  263. if (Argument == 0)
  264. {
  265. if (PreceedMatch == false)
  266. break;
  267. if (strlen(argv[I]) >= sizeof(Buffer))
  268. return _error->Error(_("Option '%s' is too long"),argv[I]);
  269. // Skip the leading dash
  270. const char *J = argv[I];
  271. for (; *J != 0 && *J == '-'; J++);
  272. const char *JEnd = strchr(J, '-');
  273. if (JEnd != NULL)
  274. {
  275. strncpy(Buffer,J,JEnd - J);
  276. Buffer[JEnd - J] = 0;
  277. Argument = Buffer;
  278. CertainArg = true;
  279. }
  280. else
  281. break;
  282. }
  283. // Check for boolean
  284. Sense = StringToBool(Argument);
  285. if (Sense >= 0)
  286. {
  287. // Eat the argument
  288. if (Argument != Buffer)
  289. {
  290. Opt += strlen(Opt);
  291. I += IncI;
  292. }
  293. break;
  294. }
  295. if (CertainArg == true)
  296. return _error->Error(_("Sense %s is not understood, try true or false."),Argument);
  297. Argument = 0;
  298. }
  299. // Indeterminate sense depends on the flag
  300. if (Sense == -1)
  301. {
  302. if ((A->Flags & InvBoolean) == InvBoolean)
  303. Sense = 0;
  304. else
  305. Sense = 1;
  306. }
  307. Conf->Set(A->ConfName,Sense);
  308. return true;
  309. }
  310. /*}}}*/
  311. // CommandLine::FileSize - Count the number of filenames /*{{{*/
  312. // ---------------------------------------------------------------------
  313. /* */
  314. unsigned int CommandLine::FileSize() const
  315. {
  316. unsigned int Count = 0;
  317. for (const char **I = FileList; I != 0 && *I != 0; I++)
  318. Count++;
  319. return Count;
  320. }
  321. /*}}}*/
  322. // CommandLine::DispatchArg - Do something with the first arg /*{{{*/
  323. // ---------------------------------------------------------------------
  324. /* */
  325. bool CommandLine::DispatchArg(Dispatch *Map,bool NoMatch)
  326. {
  327. int I;
  328. for (I = 0; Map[I].Match != 0; I++)
  329. {
  330. if (strcmp(FileList[0],Map[I].Match) == 0)
  331. {
  332. bool Res = Map[I].Handler(*this);
  333. if (Res == false && _error->PendingError() == false)
  334. _error->Error("Handler silently failed");
  335. return Res;
  336. }
  337. }
  338. // No matching name
  339. if (Map[I].Match == 0)
  340. {
  341. if (NoMatch == true)
  342. _error->Error(_("Invalid operation %s"),FileList[0]);
  343. }
  344. return false;
  345. }
  346. /*}}}*/
  347. // CommandLine::SaveInConfig - for output later in a logfile or so /*{{{*/
  348. // ---------------------------------------------------------------------
  349. /* We save the commandline here to have it around later for e.g. logging.
  350. It feels a bit like a hack here and isn't bulletproof, but it is better
  351. than nothing after all. */
  352. void CommandLine::SaveInConfig(unsigned int const &argc, char const * const * const argv)
  353. {
  354. char cmdline[100 + argc * 50];
  355. memset(cmdline, 0, sizeof(cmdline));
  356. unsigned int length = 0;
  357. bool lastWasOption = false;
  358. bool closeQuote = false;
  359. for (unsigned int i = 0; i < argc && length < sizeof(cmdline); ++i, ++length)
  360. {
  361. for (unsigned int j = 0; argv[i][j] != '\0' && length < sizeof(cmdline)-1; ++j, ++length)
  362. {
  363. cmdline[length] = argv[i][j];
  364. if (lastWasOption == true && argv[i][j] == '=')
  365. {
  366. // That is possibly an option: Quote it if it includes spaces,
  367. // the benefit is that this will eliminate also most false positives
  368. const char* c = strchr(&argv[i][j+1], ' ');
  369. if (c == NULL) continue;
  370. cmdline[++length] = '"';
  371. closeQuote = true;
  372. }
  373. }
  374. if (closeQuote == true)
  375. cmdline[length++] = '"';
  376. // Problem: detects also --hello
  377. if (cmdline[length-1] == 'o')
  378. lastWasOption = true;
  379. cmdline[length] = ' ';
  380. }
  381. cmdline[--length] = '\0';
  382. _config->Set("CommandLine::AsString", cmdline);
  383. }
  384. /*}}}*/
  385. CommandLine::Args CommandLine::MakeArgs(char ShortOpt, char const *LongOpt, char const *ConfName, unsigned long Flags)/*{{{*/
  386. {
  387. /* In theory, this should be a constructor for CommandLine::Args instead,
  388. but this breaks compatibility as gcc thinks this is a c++11 initializer_list */
  389. CommandLine::Args arg;
  390. arg.ShortOpt = ShortOpt;
  391. arg.LongOpt = LongOpt;
  392. arg.ConfName = ConfName;
  393. arg.Flags = Flags;
  394. return arg;
  395. }
  396. /*}}}*/