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