cmndline.cc 14 KB

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