generator: Code to handle optional arguments in daemon functions.
[libguestfs.git] / generator / generator_daemon.ml
1 (* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *)
18
19 (* Please read generator/README first. *)
20
21 open Printf
22
23 open Generator_types
24 open Generator_utils
25 open Generator_pr
26 open Generator_docstrings
27 open Generator_optgroups
28 open Generator_actions
29 open Generator_structs
30 open Generator_c
31
32 (* Generate daemon/actions.h. *)
33 let generate_daemon_actions_h () =
34   generate_header CStyle GPLv2plus;
35
36   pr "#include \"guestfs_protocol.h\"\n";
37   pr "\n";
38
39   List.iter (
40     function
41     | shortname, (_, _, (_::_ as optargs)), _, _, _, _, _ ->
42         iteri (
43           fun i arg ->
44             let uc_shortname = String.uppercase shortname in
45             let n = name_of_argt arg in
46             let uc_n = String.uppercase n in
47             pr "#define GUESTFS_%s_%s_BITMASK (UINT64_C(1)<<%d)\n"
48               uc_shortname uc_n i
49         ) optargs
50     | _ -> ()
51   ) daemon_functions;
52
53   List.iter (
54     fun (name, (ret, args, optargs), _, _, _, _, _) ->
55       let style = ret, args @ optargs, [] in
56       generate_prototype
57         ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
58         name style;
59   ) daemon_functions
60
61 (* Generate the server-side stubs. *)
62 and generate_daemon_actions () =
63   generate_header CStyle GPLv2plus;
64
65   pr "#include <config.h>\n";
66   pr "\n";
67   pr "#include <stdio.h>\n";
68   pr "#include <stdlib.h>\n";
69   pr "#include <string.h>\n";
70   pr "#include <inttypes.h>\n";
71   pr "#include <rpc/types.h>\n";
72   pr "#include <rpc/xdr.h>\n";
73   pr "\n";
74   pr "#include \"daemon.h\"\n";
75   pr "#include \"c-ctype.h\"\n";
76   pr "#include \"guestfs_protocol.h\"\n";
77   pr "#include \"actions.h\"\n";
78   pr "\n";
79
80   List.iter (
81     fun (name, (ret, args, optargs), _, _, _, _, _) ->
82       (* Generate server-side stubs. *)
83       pr "static void %s_stub (XDR *xdr_in)\n" name;
84       pr "{\n";
85       let error_code =
86         match ret with
87         | RErr | RInt _ -> pr "  int r;\n"; "-1"
88         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
89         | RBool _ -> pr "  int r;\n"; "-1"
90         | RConstString _ | RConstOptString _ ->
91             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
92         | RString _ -> pr "  char *r;\n"; "NULL"
93         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
94         | RStruct (_, typ) -> pr "  guestfs_int_%s *r;\n" typ; "NULL"
95         | RStructList (_, typ) -> pr "  guestfs_int_%s_list *r;\n" typ; "NULL"
96         | RBufferOut _ ->
97             pr "  size_t size = 1;\n";
98             pr "  char *r;\n";
99             "NULL" in
100
101       if args <> [] || optargs <> [] then (
102         pr "  struct guestfs_%s_args args;\n" name;
103         List.iter (
104           function
105           | Device n | Dev_or_Path n
106           | Pathname n
107           | String n
108           | Key n -> ()
109           | OptString n -> pr "  char *%s;\n" n
110           | StringList n | DeviceList n -> pr "  char **%s;\n" n
111           | Bool n -> pr "  int %s;\n" n
112           | Int n -> pr "  int %s;\n" n
113           | Int64 n -> pr "  int64_t %s;\n" n
114           | FileIn _ | FileOut _ -> ()
115           | BufferIn n ->
116               pr "  const char *%s;\n" n;
117               pr "  size_t %s_size;\n" n
118           | Pointer _ -> assert false
119         ) (args @ optargs)
120       );
121       pr "\n";
122
123       let is_filein =
124         List.exists (function FileIn _ -> true | _ -> false) args in
125
126       (* Reject unknown optional arguments. *)
127       if optargs <> [] then (
128         let len = List.length optargs in
129         let mask = Int64.lognot (Int64.pred (Int64.shift_left 1L len)) in
130         pr "  if (optargs_bitmask & UINT64_C(0x%Lx)) {\n" mask;
131         if is_filein then
132           pr "    if (cancel_receive () != -2)\n";
133         pr "    reply_with_error (\"unknown option in optional arguments bitmask (this can happen if a program is compiled against a newer version of libguestfs, then run against an older version of the daemon)\");\n";
134         pr "    goto done;\n";
135         pr "  }\n";
136         pr "\n"
137       );
138
139       (* Decode arguments. *)
140       if args <> [] || optargs <> [] then (
141         pr "  memset (&args, 0, sizeof args);\n";
142         pr "\n";
143         pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
144         if is_filein then
145           pr "    if (cancel_receive () != -2)\n";
146         pr "      reply_with_error (\"daemon failed to decode procedure arguments\");\n";
147         pr "    goto done;\n";
148         pr "  }\n";
149         let pr_args n =
150           pr "  char *%s = args.%s;\n" n n
151         in
152         let pr_list_handling_code n =
153           pr "  %s = realloc (args.%s.%s_val,\n" n n n;
154           pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
155           pr "  if (%s == NULL) {\n" n;
156           if is_filein then
157             pr "    if (cancel_receive () != -2)\n";
158           pr "      reply_with_perror (\"realloc\");\n";
159           pr "    goto done;\n";
160           pr "  }\n";
161           pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
162           pr "  args.%s.%s_val = %s;\n" n n n;
163         in
164         List.iter (
165           function
166           | Pathname n ->
167               pr_args n;
168               pr "  ABS_PATH (%s, %s, goto done);\n"
169                 n (if is_filein then "cancel_receive ()" else "0");
170           | Device n ->
171               pr_args n;
172               pr "  RESOLVE_DEVICE (%s, %s, goto done);\n"
173                 n (if is_filein then "cancel_receive ()" else "0");
174           | Dev_or_Path n ->
175               pr_args n;
176               pr "  REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, %s, goto done);\n"
177                 n (if is_filein then "cancel_receive ()" else "0");
178           | String n | Key n -> pr_args n
179           | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
180           | StringList n ->
181               pr_list_handling_code n;
182           | DeviceList n ->
183               pr_list_handling_code n;
184               pr "  /* Ensure that each is a device,\n";
185               pr "   * and perform device name translation.\n";
186               pr "   */\n";
187               pr "  {\n";
188               pr "    size_t i;\n";
189               pr "    for (i = 0; %s[i] != NULL; ++i)\n" n;
190               pr "      RESOLVE_DEVICE (%s[i], %s, goto done);\n" n
191                 (if is_filein then "cancel_receive ()" else "0");
192               pr "  }\n";
193           | Bool n -> pr "  %s = args.%s;\n" n n
194           | Int n -> pr "  %s = args.%s;\n" n n
195           | Int64 n -> pr "  %s = args.%s;\n" n n
196           | FileIn _ | FileOut _ -> ()
197           | BufferIn n ->
198               pr "  %s = args.%s.%s_val;\n" n n n;
199               pr "  %s_size = args.%s.%s_len;\n" n n n
200           | Pointer _ -> assert false
201         ) (args @ optargs);
202         pr "\n"
203       );
204
205       (* this is used at least for do_equal *)
206       if List.exists (function Pathname _ -> true | _ -> false) args then (
207         (* Emit NEED_ROOT just once, even when there are two or
208            more Pathname args *)
209         pr "  NEED_ROOT (%s, goto done);\n"
210           (if is_filein then "cancel_receive ()" else "0");
211       );
212
213       (* Don't want to call the impl with any FileIn or FileOut
214        * parameters, since these go "outside" the RPC protocol.
215        *)
216       let () =
217         let args' =
218           List.filter
219             (function FileIn _ | FileOut _ -> false | _ -> true) args in
220         let style = ret, args' @ optargs, [] in
221         pr "  r = do_%s " name;
222         generate_c_call_args style;
223         pr ";\n" in
224
225       (match ret with
226        | RErr | RInt _ | RInt64 _ | RBool _
227        | RConstString _ | RConstOptString _
228        | RString _ | RStringList _ | RHashtable _
229        | RStruct (_, _) | RStructList (_, _) ->
230            pr "  if (r == %s)\n" error_code;
231            pr "    /* do_%s has already called reply_with_error */\n" name;
232            pr "    goto done;\n";
233            pr "\n"
234        | RBufferOut _ ->
235            pr "  /* size == 0 && r == NULL could be a non-error case (just\n";
236            pr "   * an ordinary zero-length buffer), so be careful ...\n";
237            pr "   */\n";
238            pr "  if (size == 1 && r == %s)\n" error_code;
239            pr "    /* do_%s has already called reply_with_error */\n" name;
240            pr "    goto done;\n";
241            pr "\n"
242       );
243
244       (* If there are any FileOut parameters, then the impl must
245        * send its own reply.
246        *)
247       let no_reply =
248         List.exists (function FileOut _ -> true | _ -> false) args in
249       if no_reply then
250         pr "  /* do_%s has already sent a reply */\n" name
251       else (
252         match ret with
253         | RErr -> pr "  reply (NULL, NULL);\n"
254         | RInt n | RInt64 n | RBool n ->
255             pr "  struct guestfs_%s_ret ret;\n" name;
256             pr "  ret.%s = r;\n" n;
257             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
258               name
259         | RConstString _ | RConstOptString _ ->
260             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
261         | RString n ->
262             pr "  struct guestfs_%s_ret ret;\n" name;
263             pr "  ret.%s = r;\n" n;
264             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
265               name;
266             pr "  free (r);\n"
267         | RStringList n | RHashtable n ->
268             pr "  struct guestfs_%s_ret ret;\n" name;
269             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
270             pr "  ret.%s.%s_val = r;\n" n n;
271             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
272               name;
273             pr "  free_strings (r);\n"
274         | RStruct (n, _) ->
275             pr "  struct guestfs_%s_ret ret;\n" name;
276             pr "  ret.%s = *r;\n" n;
277             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
278               name;
279             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
280               name
281         | RStructList (n, _) ->
282             pr "  struct guestfs_%s_ret ret;\n" name;
283             pr "  ret.%s = *r;\n" n;
284             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
285               name;
286             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
287               name
288         | RBufferOut n ->
289             pr "  struct guestfs_%s_ret ret;\n" name;
290             pr "  ret.%s.%s_val = r;\n" n n;
291             pr "  ret.%s.%s_len = size;\n" n n;
292             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
293               name;
294             pr "  free (r);\n"
295       );
296
297       (* Free the args. *)
298       pr "done:\n";
299       (match args with
300        | [] -> ()
301        | _ ->
302            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
303              name
304       );
305       pr "  return;\n";
306       pr "}\n\n";
307   ) daemon_functions;
308
309   (* Dispatch function. *)
310   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
311   pr "{\n";
312   pr "  switch (proc_nr) {\n";
313
314   List.iter (
315     fun (name, _, _, _, _, _, _) ->
316       pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
317       pr "      %s_stub (xdr_in);\n" name;
318       pr "      break;\n"
319   ) daemon_functions;
320
321   pr "    default:\n";
322   pr "      reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d, set LIBGUESTFS_PATH to point to the matching libguestfs appliance directory\", proc_nr);\n";
323   pr "  }\n";
324   pr "}\n";
325   pr "\n";
326
327   (* LVM columns and tokenization functions. *)
328   (* XXX This generates crap code.  We should rethink how we
329    * do this parsing.
330    *)
331   List.iter (
332     function
333     | typ, cols ->
334         pr "static const char *lvm_%s_cols = \"%s\";\n"
335           typ (String.concat "," (List.map fst cols));
336         pr "\n";
337
338         pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
339         pr "{\n";
340         pr "  char *tok, *p, *next;\n";
341         pr "  size_t i, j;\n";
342         pr "\n";
343         (*
344           pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
345           pr "\n";
346         *)
347         pr "  if (!str) {\n";
348         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
349         pr "    return -1;\n";
350         pr "  }\n";
351         pr "  if (!*str || c_isspace (*str)) {\n";
352         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
353         pr "    return -1;\n";
354         pr "  }\n";
355         pr "  tok = str;\n";
356         List.iter (
357           fun (name, coltype) ->
358             pr "  if (!tok) {\n";
359             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
360             pr "    return -1;\n";
361             pr "  }\n";
362             pr "  p = strchrnul (tok, ',');\n";
363             pr "  if (*p) next = p+1; else next = NULL;\n";
364             pr "  *p = '\\0';\n";
365             (match coltype with
366              | FString ->
367                  pr "  r->%s = strdup (tok);\n" name;
368                  pr "  if (r->%s == NULL) {\n" name;
369                  pr "    perror (\"strdup\");\n";
370                  pr "    return -1;\n";
371                  pr "  }\n"
372              | FUUID ->
373                  pr "  for (i = j = 0; i < 32; ++j) {\n";
374                  pr "    if (tok[j] == '\\0') {\n";
375                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
376                  pr "      return -1;\n";
377                  pr "    } else if (tok[j] != '-')\n";
378                  pr "      r->%s[i++] = tok[j];\n" name;
379                  pr "  }\n";
380              | FBytes ->
381                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
382                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
383                  pr "    return -1;\n";
384                  pr "  }\n";
385              | FInt64 ->
386                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
387                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
388                  pr "    return -1;\n";
389                  pr "  }\n";
390              | FOptPercent ->
391                  pr "  if (tok[0] == '\\0')\n";
392                  pr "    r->%s = -1;\n" name;
393                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
394                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
395                  pr "    return -1;\n";
396                  pr "  }\n";
397              | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
398                  assert false (* can never be an LVM column *)
399             );
400             pr "  tok = next;\n";
401         ) cols;
402
403         pr "  if (tok != NULL) {\n";
404         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
405         pr "    return -1;\n";
406         pr "  }\n";
407         pr "  return 0;\n";
408         pr "}\n";
409         pr "\n";
410
411         pr "guestfs_int_lvm_%s_list *\n" typ;
412         pr "parse_command_line_%ss (void)\n" typ;
413         pr "{\n";
414         pr "  char *out, *err;\n";
415         pr "  char *p, *pend;\n";
416         pr "  int r, i;\n";
417         pr "  guestfs_int_lvm_%s_list *ret;\n" typ;
418         pr "  void *newp;\n";
419         pr "\n";
420         pr "  ret = malloc (sizeof *ret);\n";
421         pr "  if (!ret) {\n";
422         pr "    reply_with_perror (\"malloc\");\n";
423         pr "    return NULL;\n";
424         pr "  }\n";
425         pr "\n";
426         pr "  ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
427         pr "  ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
428         pr "\n";
429         pr "  r = command (&out, &err,\n";
430         pr "           \"lvm\", \"%ss\",\n" typ;
431         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
432         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
433         pr "  if (r == -1) {\n";
434         pr "    reply_with_error (\"%%s\", err);\n";
435         pr "    free (out);\n";
436         pr "    free (err);\n";
437         pr "    free (ret);\n";
438         pr "    return NULL;\n";
439         pr "  }\n";
440         pr "\n";
441         pr "  free (err);\n";
442         pr "\n";
443         pr "  /* Tokenize each line of the output. */\n";
444         pr "  p = out;\n";
445         pr "  i = 0;\n";
446         pr "  while (p) {\n";
447         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
448         pr "    if (pend) {\n";
449         pr "      *pend = '\\0';\n";
450         pr "      pend++;\n";
451         pr "    }\n";
452         pr "\n";
453         pr "    while (*p && c_isspace (*p))    /* Skip any leading whitespace. */\n";
454         pr "      p++;\n";
455         pr "\n";
456         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
457         pr "      p = pend;\n";
458         pr "      continue;\n";
459         pr "    }\n";
460         pr "\n";
461         pr "    /* Allocate some space to store this next entry. */\n";
462         pr "    newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
463         pr "                sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
464         pr "    if (newp == NULL) {\n";
465         pr "      reply_with_perror (\"realloc\");\n";
466         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
467         pr "      free (ret);\n";
468         pr "      free (out);\n";
469         pr "      return NULL;\n";
470         pr "    }\n";
471         pr "    ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
472         pr "\n";
473         pr "    /* Tokenize the next entry. */\n";
474         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
475         pr "    if (r == -1) {\n";
476         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
477         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
478         pr "      free (ret);\n";
479         pr "      free (out);\n";
480         pr "      return NULL;\n";
481         pr "    }\n";
482         pr "\n";
483         pr "    ++i;\n";
484         pr "    p = pend;\n";
485         pr "  }\n";
486         pr "\n";
487         pr "  ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
488         pr "\n";
489         pr "  free (out);\n";
490         pr "  return ret;\n";
491         pr "}\n"
492
493   ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
494
495 (* Generate a list of function names, for debugging in the daemon.. *)
496 and generate_daemon_names () =
497   generate_header CStyle GPLv2plus;
498
499   pr "#include <config.h>\n";
500   pr "\n";
501   pr "#include \"daemon.h\"\n";
502   pr "\n";
503
504   pr "/* This array is indexed by proc_nr.  See guestfs_protocol.x. */\n";
505   pr "const char *function_names[] = {\n";
506   List.iter (
507     fun (name, _, proc_nr, _, _, _, _) -> pr "  [%d] = \"%s\",\n" proc_nr name
508   ) daemon_functions;
509   pr "};\n";
510
511 (* Generate the optional groups for the daemon to implement
512  * guestfs_available.
513  *)
514 and generate_daemon_optgroups_c () =
515   generate_header CStyle GPLv2plus;
516
517   pr "#include <config.h>\n";
518   pr "\n";
519   pr "#include \"daemon.h\"\n";
520   pr "#include \"optgroups.h\"\n";
521   pr "\n";
522
523   pr "struct optgroup optgroups[] = {\n";
524   List.iter (
525     fun (group, _) ->
526       pr "  { \"%s\", optgroup_%s_available },\n" group group
527   ) optgroups;
528   pr "  { NULL, NULL }\n";
529   pr "};\n"
530
531 and generate_daemon_optgroups_h () =
532   generate_header CStyle GPLv2plus;
533
534   List.iter (
535     fun (group, _) ->
536       pr "extern int optgroup_%s_available (void);\n" group
537   ) optgroups