Support 'help command_name' as the equivalent of 'command_name --help'.
[captive.git] / src / client / cmdline / main.c
1 /* $Id$
2  * client cmdline interface for libcaptive
3  * Copyright (C) 2002-2003 Jan Kratochvil <project-captive@jankratochvil.net>
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; exactly version 2 of June 1991 is required
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19
20 #include "config.h"
21
22 #include <glib/gmessages.h>
23 #include <stdlib.h>
24 #include <glib/giochannel.h>
25 #include <glib/gerror.h>
26 #include <popt.h>
27 #include <string.h>
28 #include <stdio.h>
29 #include <locale.h>
30
31 #include <captive/client-vfs.h>
32
33 #include "main.h"       /* self */
34 #include "cmd_shell.h"
35 #include "cmd_cd.h"
36 #include "cmd_lcd.h"
37 #include "cmd_ls.h"
38 #include "cmd_get.h"
39 #include "cmd_put.h"
40 #include "cmd_info.h"
41 #include "cmd_volume.h"
42 #include "cmd_rm.h"
43 #include "cmd_mv.h"
44 #include "cmd_mkdir.h"
45 #include "cmd_rmdir.h"
46 #include "cmd_commit.h"
47 #include "cmd_quit.h"
48 #include "cmd_help.h"
49
50
51 CaptiveVfsObject *cmdline_captive_vfs_object;
52
53
54 GQuark cmdline_main_error_quark(void)
55 {
56 GQuark r=0;
57
58         if (!r)
59                 r=g_quark_from_static_string("cmdline-main");
60
61         return r;
62 }
63
64
65 static const struct poptOption popt_table[]={
66                 CAPTIVE_POPT_INCLUDE,
67                 POPT_AUTOHELP
68                 POPT_TABLEEND
69                 };
70
71 const struct cmdline_command cmdline_command_table[]={
72                 /* First entry is the default if no command name was specified. */
73                 { "shell" ,N_("Interactive commands shell.")                        ,cmd_shell_table ,cmd_shell ,0,0 },
74                 { "cd"    ,N_("Print or change current guest-os directory[1].")     ,cmd_cd_table    ,cmd_cd    ,0,1 },
75                 { "lcd"   ,N_("Print or change current host-os  directory[1].")     ,cmd_lcd_table   ,cmd_lcd   ,0,1 },
76                 { "ls"    ,N_("Directory[1] listing.")                              ,cmd_ls_table    ,cmd_ls    ,0,1 },
77                 { "get"   ,N_("Copy guest-os file[1] to host-os (opt. file[2]).")   ,cmd_get_table   ,cmd_get   ,1,2 },
78                 { "put"   ,N_("Copy host-os file[1] to guest-os (opt. file[2]).")   ,cmd_put_table   ,cmd_put   ,1,2 },
79                 { "info"  ,N_("Query information about guest-os item[1].")          ,cmd_info_table  ,cmd_info  ,1,1 },
80                 { "volume",N_("Query information about guest-os volume.")           ,cmd_volume_table,cmd_volume,0,0 },
81                 { "rm"    ,N_("Remove guest-os file[1].")                           ,cmd_rm_table    ,cmd_rm    ,1,1 },
82                 { "mv"    ,N_("Move (rename) guest-os item[1] to guest-os item[2]."),cmd_mv_table    ,cmd_mv    ,2,2 },
83                 { "mkdir" ,N_("Create guest-os directory[1].")                      ,cmd_mkdir_table ,cmd_mkdir ,1,1 },
84                 { "rmdir" ,N_("Remove guest-os directory[1].")                      ,cmd_rmdir_table ,cmd_rmdir ,1,1 },
85                 { "commit",N_("Write any pending changes and remount the volume.")  ,cmd_commit_table,cmd_commit,0,0 },
86                 { "quit"  ,N_("Quit this program.")                                 ,cmd_quit_table  ,cmd_quit  ,0,0 },
87                 { "help"  ,N_("Show this list of commands or help for command[1].") ,cmd_help_table  ,cmd_help  ,0,1 },
88                 { NULL },       /* G_N_ELEMENTS() not usable as sizeof() is not visible for 'extern' */
89                 };
90
91
92 static gboolean displayArgs_hit;
93
94 static void displayArgs(poptContext con,enum poptCallbackReason foo,struct poptOption *key,const char *arg,void *data)
95 {
96         displayArgs_hit=TRUE;
97
98         if (key->shortName=='?')
99                 poptPrintHelp(con,stdout,0);
100         else
101                 poptPrintUsage(con,stdout,0);
102 }
103
104 const struct poptOption cmdline_poptHelpOptions[]={
105                 { argInfo:POPT_ARG_INTL_DOMAIN,arg:"popt" },
106                 { NULL   ,'\0',POPT_ARG_CALLBACK,(void *)&displayArgs,'\0',NULL,NULL },
107                 { "help" ,'?' ,0                ,NULL,'?',/* N_ */("Show this help message"),     NULL },
108                 { "usage",'\0',0                ,NULL,'u',/* N_ */("Display brief usage message"),NULL },
109                 POPT_TABLEEND
110                 };
111
112
113 static void invoke_cmd_err(int cmd_argc,const char **cmd_argv,GError **errp)
114 {
115 const struct cmdline_command *commandp;
116 const char *cmd_name=NULL;
117 poptContext cmd_context;
118 int errint;
119 const char **cmdarg_argv;
120 int cmdarg_argc;
121 const char **csp;
122 const char *emptyargv_NULL=NULL;
123
124         g_return_if_fail(cmd_argc>=0);
125         g_return_if_fail(!errp || !*errp);
126
127         /* poptGetContext() cannot be passed argc==0 even if we lass POPT_CONTEXT_KEEP_FIRST
128          * as it is buggy. Workaround it by keeping the command name as argv[0].
129          */
130         if (!cmd_argc) {
131 const char *stub_shell[]={ cmdline_command_table[0].name,NULL };
132                 
133                 cmd_argc=1;
134                 cmd_argv=stub_shell;
135                 }
136
137         cmd_name=*cmd_argv;
138         for (commandp=cmdline_command_table;commandp->name;commandp++) {
139                 if (!cmd_name   /* NULL cmd_name fallback to the first table entry - "shell" */
140                                 || !strcasecmp(cmd_name,commandp->name))
141                         break;
142                 }
143         if (!commandp->name) {
144                 g_set_error(errp,CMDLINE_MAIN_ERROR,CMDLINE_MAIN_ERROR_UNKNOWN_COMMAND,
145                                 _("Unknown command, try 'help': %s"),cmd_name);
146                 return;
147                 }
148         displayArgs_hit=FALSE;
149         cmd_context=poptGetContext(
150                         PACKAGE,        /* name */
151                         cmd_argc,cmd_argv,      /* argc,argv */
152                         commandp->table,        /* options */
153                         POPT_CONTEXT_POSIXMEHARDER);    /* flags; !POPT_CONTEXT_KEEP_FIRST */
154         if (cmd_context==NULL) {
155                 g_set_error(errp,CMDLINE_MAIN_ERROR,CMDLINE_MAIN_ERROR_INVALID_COMMAND_ARGUMENTS,
156                                 _("Invalid arguments for command: %s"),cmd_name);
157                 return;
158                 }
159         errint=poptReadDefaultConfig(cmd_context,
160                         TRUE);  /* useEnv */
161         if (errint!=0) {
162                 g_set_error(errp,CMDLINE_MAIN_ERROR,CMDLINE_MAIN_ERROR_READING_COMMAND_CONFIG,
163                                 _("Error '%s' reading default configuration for command: %s"),poptStrerror(errint),cmd_name);
164                 goto err_free_context;
165                 }
166         errint=poptGetNextOpt(cmd_context);
167         if (errint!=-1) {
168                 g_set_error(errp,CMDLINE_MAIN_ERROR,CMDLINE_MAIN_ERROR_EXCEEDING_COMMAND_OPTION,
169                                 _("Exceeding command option for command: %s"),cmd_name);
170                 goto err_free_context;
171                 }
172         if (!(cmdarg_argv=poptGetArgs(cmd_context)))
173                 cmdarg_argv=&emptyargv_NULL;
174
175         if (displayArgs_hit)
176                 goto err_free_context;
177         
178         for (csp=cmdarg_argv,cmdarg_argc=0;*csp;csp++)
179                 cmdarg_argc++;
180         if (cmdarg_argc<commandp->argsn_min || cmdarg_argc>commandp->argsn_max) {
181                 g_set_error(errp,CMDLINE_MAIN_ERROR,CMDLINE_MAIN_ERROR_INVALID_COMMAND_ARGUMENT_COUNT,
182                                 _("Invalid number of command '%s' arguments: %d; expected from %d to %d incl."),
183                                 cmd_name,cmdarg_argc,commandp->argsn_min,commandp->argsn_max);
184                 goto err_free_context;
185                 }
186
187         (*commandp->func)(cmdarg_argv,errp);
188
189 err_free_context:
190         poptFreeContext(cmd_context);
191 }
192
193
194 void err_cleanup(GError **errp)
195 {
196         g_return_if_fail(errp!=NULL);
197
198         if (!*errp)
199                 return;
200         printf("\nERROR: %s\n",(*errp)->message);
201         g_clear_error(errp);
202 }
203
204
205 void invoke_cmd(int cmd_argc,const char **cmd_argv)
206 {
207 GError *gerr=NULL;
208
209         invoke_cmd_err(cmd_argc,cmd_argv,&gerr);
210         err_cleanup(&gerr);
211 }
212
213
214 /* Returns: Success (no error occured). */
215 gboolean errvfsresult_to_gerr(GError **errp,GnomeVFSResult errvfsresult)
216 {
217         g_return_val_if_fail(!errp || !*errp,FALSE);
218
219         if (errvfsresult==GNOME_VFS_OK)
220                 return TRUE;
221
222         g_set_error(errp,CMDLINE_MAIN_ERROR,CMDLINE_MAIN_ERROR_GENERIC_ERROR,
223                         _("Generic error: %s"),gnome_vfs_result_to_string(errvfsresult));
224         return FALSE;
225 }
226
227 static GIOChannel *main_giochannel;
228
229 void main_exit(void) G_GNUC_NORETURN;
230 void main_exit(void)
231 {
232         if (cmdline_captive_vfs_object) {
233                 g_object_unref(cmdline_captive_vfs_object);
234                 cmdline_captive_vfs_object=NULL;
235                 }
236         if (main_giochannel) {
237                 g_io_channel_unref(main_giochannel);
238                 main_giochannel=NULL;
239                 }
240         exit(EXIT_SUCCESS);
241 }
242
243 int main(int argc,char **argv)
244 {
245 poptContext context;
246 int errint;
247 const char **cmd_argv,**csp;
248 int cmd_argc;
249 GError *gerr=NULL;
250 struct captive_options options;
251
252         /* Do not set g_log_set_always_fatal() here as we would not be able
253          * to restart failed children due to communication-failure alarms.
254          */
255
256         /* Prevent output block buffering if redirecting stdout to file. */
257         setvbuf(stdout,(char *)NULL,_IONBF,0);
258         setvbuf(stderr,(char *)NULL,_IONBF,0);
259
260         /* Initialize the i18n stuff */
261         setlocale(LC_ALL,"");
262         bindtextdomain(PACKAGE,LOCALEDIR);
263         textdomain(PACKAGE);
264
265         /* Initialize GObject subsystem of GLib. */
266         g_type_init();
267
268         captive_options_init(&options);
269         captive_options=&options;       /* for parsing by 'CAPTIVE_POPT_INCLUDE' */
270
271         context=poptGetContext(
272                         PACKAGE,        /* name */
273                         argc,(/*en-const*/const char **)argv,   /* argc,argv */
274                         popt_table,     /* options */
275                         POPT_CONTEXT_POSIXMEHARDER);    /* flags; && !POPT_CONTEXT_KEEP_FIRST */
276         if (context==NULL) {
277                 g_error(_("Error parsing command-line arguments"));
278                 return EXIT_FAILURE;
279                 }
280         errint=poptReadDefaultConfig(context,
281                         TRUE);  /* useEnv */
282         if (errint!=0)
283                 g_warning(_("Error reading default popt configuration"));
284         errint=poptGetNextOpt(context);
285         if (errint!=-1) {
286                 g_error(_("Error parsing (dash-prefixed) command-line argument"));
287                 return EXIT_FAILURE;
288                 }
289         cmd_argv=poptGetArgs(context);
290         for (csp=cmd_argv,cmd_argc=0;csp && *csp;csp++)
291                 cmd_argc++;
292
293         captive_options=NULL;   /* already parsed by 'CAPTIVE_POPT_INCLUDE' */
294
295         /* image_iochannel */
296         if (cmd_argc<=0) {
297                 g_error(_("File/device disk image pathname command-line argument required"));
298                 return EXIT_FAILURE;
299                 }
300         g_assert(options.image_iochannel==NULL);
301         if (!(options.image_iochannel=g_io_channel_new_file(
302                         cmd_argv[0],    /* filename */
303                         (options.rwmode==CAPTIVE_OPTION_RWMODE_RW ? "r+" : "r"),        /* mode */
304                         NULL))) {       /* error */
305                 g_error(_("image_iochannel open failed"));
306                 return EXIT_FAILURE;
307                 }
308         cmd_argc--;
309         cmd_argv++;
310
311         if (options.filesystem.type==CAPTIVE_OPTIONS_MODULE_TYPE_EMPTY) {
312                 g_error(_("'--filesystem' option required ('ntfs.sys' pathname suggested)"));
313                 return EXIT_FAILURE;
314                 }
315         if (!options.load_module) {
316                 g_warning(_("'--load-module' option required ('ntoskrnl.exe' pathname suggested)"));
317                 return EXIT_FAILURE;
318                 }
319
320         if (GNOME_VFS_OK!=captive_vfs_new(&cmdline_captive_vfs_object,&options)) {
321                 g_error(_("captive_vfs_new() failed"));
322                 return EXIT_FAILURE;
323                 }
324         captive_options_free(&options);
325
326         cmd_cd_internal("/",&gerr);
327         if (gerr) {
328                 err_cleanup(&gerr);
329                 return EXIT_FAILURE;
330                 }
331
332         invoke_cmd(cmd_argc,cmd_argv);
333
334         /* 'cmd_argv' gets cleared by 'poptFreeContext(context);' below */
335         poptFreeContext(context);
336
337         main_exit();    /* unref 'cmdline_captive_vfs_object' */
338         /* NOTREACHED */
339 }