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