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