cmndline.cc 13 KB

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