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