cmndline.cc 12 KB

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