cmndline.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 understood in combination with the other options."),*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 in combination with the other options"),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 in combination with the other options"),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 in combination with the other options"),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)
  184. {
  185. if (I + 1 < argc && argv[I+1][0] != '-')
  186. Argument = argv[I+1];
  187. IncI = 1;
  188. }
  189. else
  190. {
  191. if (Opt[1] == '=')
  192. {
  193. CertainArg = true;
  194. Argument = Opt + 2;
  195. }
  196. else
  197. Argument = Opt + 1;
  198. }
  199. // Option is an argument set
  200. if ((A->Flags & HasArg) == HasArg)
  201. {
  202. if (Argument == 0)
  203. return _error->Error(_("Option %s requires an argument."),argv[I]);
  204. Opt += strlen(Opt);
  205. I += IncI;
  206. // Parse a configuration file
  207. if ((A->Flags & ConfigFile) == ConfigFile)
  208. return ReadConfigFile(*Conf,Argument);
  209. // Arbitrary item specification
  210. if ((A->Flags & ArbItem) == ArbItem)
  211. {
  212. const char * const J = strchr(Argument, '=');
  213. if (J == nullptr)
  214. return _error->Error(_("Option %s: Configuration item specification must have an =<val>."),argv[I]);
  215. Conf->Set(string(Argument,J-Argument), J+1);
  216. return true;
  217. }
  218. const char *I = strchrnul(A->ConfName, ' ');
  219. if (*I == ' ')
  220. Conf->Set(string(A->ConfName,0,I-A->ConfName),string(I+1) + Argument);
  221. else
  222. Conf->Set(A->ConfName,string(I) + Argument);
  223. return true;
  224. }
  225. // Option is an integer level
  226. if ((A->Flags & IntLevel) == IntLevel)
  227. {
  228. // There might be an argument
  229. if (Argument != 0)
  230. {
  231. char *EndPtr;
  232. unsigned long Value = strtol(Argument,&EndPtr,10);
  233. // Conversion failed and the argument was specified with an =s
  234. if (EndPtr == Argument && CertainArg == true)
  235. return _error->Error(_("Option %s requires an integer argument, not '%s'"),argv[I],Argument);
  236. // Conversion was ok, set the value and return
  237. if (EndPtr != 0 && EndPtr != Argument && *EndPtr == 0)
  238. {
  239. Conf->Set(A->ConfName,Value);
  240. Opt += strlen(Opt);
  241. I += IncI;
  242. return true;
  243. }
  244. }
  245. // Increase the level
  246. Conf->Set(A->ConfName,Conf->FindI(A->ConfName)+1);
  247. return true;
  248. }
  249. // Option is a boolean
  250. int Sense = -1; // -1 is unspecified, 0 is yes 1 is no
  251. // Look for an argument.
  252. while (1)
  253. {
  254. // Look at preceding text
  255. char Buffer[300];
  256. if (Argument == 0)
  257. {
  258. if (PreceedMatch == false)
  259. break;
  260. if (strlen(argv[I]) >= sizeof(Buffer))
  261. return _error->Error(_("Option '%s' is too long"),argv[I]);
  262. // Skip the leading dash
  263. const char *J = argv[I];
  264. for (; *J != 0 && *J == '-'; J++);
  265. const char *JEnd = strchr(J, '-');
  266. if (JEnd != NULL)
  267. {
  268. strncpy(Buffer,J,JEnd - J);
  269. Buffer[JEnd - J] = 0;
  270. Argument = Buffer;
  271. CertainArg = true;
  272. }
  273. else
  274. break;
  275. }
  276. // Check for boolean
  277. Sense = StringToBool(Argument);
  278. if (Sense >= 0)
  279. {
  280. // Eat the argument
  281. if (Argument != Buffer)
  282. {
  283. Opt += strlen(Opt);
  284. I += IncI;
  285. }
  286. break;
  287. }
  288. if (CertainArg == true)
  289. return _error->Error(_("Sense %s is not understood, try true or false."),Argument);
  290. Argument = 0;
  291. }
  292. // Indeterminate sense depends on the flag
  293. if (Sense == -1)
  294. {
  295. if ((A->Flags & InvBoolean) == InvBoolean)
  296. Sense = 0;
  297. else
  298. Sense = 1;
  299. }
  300. Conf->Set(A->ConfName,Sense);
  301. return true;
  302. }
  303. /*}}}*/
  304. // CommandLine::FileSize - Count the number of filenames /*{{{*/
  305. // ---------------------------------------------------------------------
  306. /* */
  307. unsigned int CommandLine::FileSize() const
  308. {
  309. unsigned int Count = 0;
  310. for (const char **I = FileList; I != 0 && *I != 0; I++)
  311. Count++;
  312. return Count;
  313. }
  314. /*}}}*/
  315. // CommandLine::DispatchArg - Do something with the first arg /*{{{*/
  316. bool CommandLine::DispatchArg(Dispatch const * const Map,bool NoMatch)
  317. {
  318. int I;
  319. for (I = 0; Map[I].Match != 0; I++)
  320. {
  321. if (strcmp(FileList[0],Map[I].Match) == 0)
  322. {
  323. bool Res = Map[I].Handler(*this);
  324. if (Res == false && _error->PendingError() == false)
  325. _error->Error("Handler silently failed");
  326. return Res;
  327. }
  328. }
  329. // No matching name
  330. if (Map[I].Match == 0)
  331. {
  332. if (NoMatch == true)
  333. _error->Error(_("Invalid operation %s"),FileList[0]);
  334. }
  335. return false;
  336. }
  337. bool CommandLine::DispatchArg(Dispatch *Map,bool NoMatch)
  338. {
  339. Dispatch const * const Map2 = Map;
  340. return DispatchArg(Map2, NoMatch);
  341. }
  342. /*}}}*/
  343. // CommandLine::SaveInConfig - for output later in a logfile or so /*{{{*/
  344. // ---------------------------------------------------------------------
  345. /* We save the commandline here to have it around later for e.g. logging.
  346. It feels a bit like a hack here and isn't bulletproof, but it is better
  347. than nothing after all. */
  348. void CommandLine::SaveInConfig(unsigned int const &argc, char const * const * const argv)
  349. {
  350. char cmdline[100 + argc * 50];
  351. memset(cmdline, 0, sizeof(cmdline));
  352. unsigned int length = 0;
  353. bool lastWasOption = false;
  354. bool closeQuote = false;
  355. for (unsigned int i = 0; i < argc && length < sizeof(cmdline); ++i, ++length)
  356. {
  357. for (unsigned int j = 0; argv[i][j] != '\0' && length < sizeof(cmdline)-1; ++j, ++length)
  358. {
  359. cmdline[length] = argv[i][j];
  360. if (lastWasOption == true && argv[i][j] == '=')
  361. {
  362. // That is possibly an option: Quote it if it includes spaces,
  363. // the benefit is that this will eliminate also most false positives
  364. const char* c = strchr(&argv[i][j+1], ' ');
  365. if (c == NULL) continue;
  366. cmdline[++length] = '"';
  367. closeQuote = true;
  368. }
  369. }
  370. if (closeQuote == true)
  371. cmdline[length++] = '"';
  372. // Problem: detects also --hello
  373. if (cmdline[length-1] == 'o')
  374. lastWasOption = true;
  375. cmdline[length] = ' ';
  376. }
  377. cmdline[--length] = '\0';
  378. _config->Set("CommandLine::AsString", cmdline);
  379. }
  380. /*}}}*/
  381. CommandLine::Args CommandLine::MakeArgs(char ShortOpt, char const *LongOpt, char const *ConfName, unsigned long Flags)/*{{{*/
  382. {
  383. /* In theory, this should be a constructor for CommandLine::Args instead,
  384. but this breaks compatibility as gcc thinks this is a c++11 initializer_list */
  385. CommandLine::Args arg;
  386. arg.ShortOpt = ShortOpt;
  387. arg.LongOpt = LongOpt;
  388. arg.ConfName = ConfName;
  389. arg.Flags = Flags;
  390. return arg;
  391. }
  392. /*}}}*/