s3-includes: only include system/passwd.h when needed.
[kai/samba.git] / source3 / utils / net_usershare.c
1 /*
2    Samba Unix/Linux SMB client library
3    Distributed SMB/CIFS Server Management Utility
4
5    Copyright (C) Jeremy Allison (jra@samba.org) 2005
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/passwd.h"
23 #include "utils/net.h"
24 #include "../libcli/security/security.h"
25
26 struct {
27         const char *us_errstr;
28         enum usershare_err us_err;
29 } us_errs [] = {
30         {"",USERSHARE_OK},
31         {N_("Malformed usershare file"), USERSHARE_MALFORMED_FILE},
32         {N_("Bad version number"), USERSHARE_BAD_VERSION},
33         {N_("Malformed path entry"), USERSHARE_MALFORMED_PATH},
34         {N_("Malformed comment entryfile"), USERSHARE_MALFORMED_COMMENT_DEF},
35         {N_("Malformed acl definition"), USERSHARE_MALFORMED_ACL_DEF},
36         {N_("Acl parse error"), USERSHARE_ACL_ERR},
37         {N_("Path not absolute"), USERSHARE_PATH_NOT_ABSOLUTE},
38         {N_("Path is denied"), USERSHARE_PATH_IS_DENIED},
39         {N_("Path not allowed"), USERSHARE_PATH_NOT_ALLOWED},
40         {N_("Path is not a directory"), USERSHARE_PATH_NOT_DIRECTORY},
41         {N_("System error"), USERSHARE_POSIX_ERR},
42         {N_("Malformed sharename definition"), USERSHARE_MALFORMED_SHARENAME_DEF},
43         {N_("Bad sharename (doesn't match filename)"), USERSHARE_BAD_SHARENAME},
44         {NULL,(enum usershare_err)-1}
45 };
46
47 static const char *get_us_error_code(enum usershare_err us_err)
48 {
49         char *result;
50         int idx = 0;
51
52         while (us_errs[idx].us_errstr != NULL) {
53                 if (us_errs[idx].us_err == us_err) {
54                         return us_errs[idx].us_errstr;
55                 }
56                 idx++;
57         }
58
59         result = talloc_asprintf(talloc_tos(), _("Usershare error code (0x%x)"),
60                                  (unsigned int)us_err);
61         SMB_ASSERT(result != NULL);
62         return result;
63 }
64
65 /* The help subsystem for the USERSHARE subcommand */
66
67 static int net_usershare_add_usage(struct net_context *c, int argc, const char **argv)
68 {
69         char chr = *lp_winbind_separator();
70         d_printf(_(
71                 "net usershare add [-l|--long] <sharename> <path> [<comment>] [<acl>] [<guest_ok=[y|n]>]\n"
72                 "\tAdds the specified share name for this user.\n"
73                 "\t<sharename> is the new share name.\n"
74                 "\t<path> is the path on the filesystem to export.\n"
75                 "\t<comment> is the optional comment for the new share.\n"
76                 "\t<acl> is an optional share acl in the format \"DOMAIN%cname:X,DOMAIN%cname:X,....\"\n"
77                 "\t<guest_ok=y> if present sets \"guest ok = yes\" on this usershare.\n"
78                 "\t\t\"X\" represents a permission and can be any one of the characters f, r or d\n"
79                 "\t\twhere \"f\" means full control, \"r\" means read-only, \"d\" means deny access.\n"
80                 "\t\tname may be a domain user or group. For local users use the local server name "
81                 "instead of \"DOMAIN\"\n"
82                 "\t\tThe default acl is \"Everyone:r\" which allows everyone read-only access.\n"
83                 "\tAdd -l or --long to print the info on the newly added share.\n"),
84                 chr, chr );
85         return -1;
86 }
87
88 static int net_usershare_delete_usage(struct net_context *c, int argc, const char **argv)
89 {
90         d_printf(_(
91                 "net usershare delete <sharename>\n"
92                 "\tdeletes the specified share name for this user.\n"));
93         return -1;
94 }
95
96 static int net_usershare_info_usage(struct net_context *c, int argc, const char **argv)
97 {
98         d_printf(_(
99                 "net usershare info [-l|--long] [wildcard sharename]\n"
100                 "\tPrints out the path, comment and acl elements of shares that match the wildcard.\n"
101                 "\tBy default only gives info on shares owned by the current user\n"
102                 "\tAdd -l or --long to apply this to all shares\n"
103                 "\tOmit the sharename or use a wildcard of '*' to see all shares\n"));
104         return -1;
105 }
106
107 static int net_usershare_list_usage(struct net_context *c, int argc, const char **argv)
108 {
109         d_printf(_(
110                 "net usershare list [-l|--long] [wildcard sharename]\n"
111                 "\tLists the names of all shares that match the wildcard.\n"
112                 "\tBy default only lists shares owned by the current user\n"
113                 "\tAdd -l or --long to apply this to all shares\n"
114                 "\tOmit the sharename or use a wildcard of '*' to see all shares\n"));
115         return -1;
116 }
117
118 int net_usershare_usage(struct net_context *c, int argc, const char **argv)
119 {
120         d_printf(_("net usershare add <sharename> <path> [<comment>] [<acl>] [<guest_ok=[y|n]>] to "
121                                 "add or change a user defined share.\n"
122                 "net usershare delete <sharename> to delete a user defined share.\n"
123                 "net usershare info [-l|--long] [wildcard sharename] to print info about a user defined share.\n"
124                 "net usershare list [-l|--long] [wildcard sharename] to list user defined shares.\n"
125                 "net usershare help\n"
126                 "\nType \"net usershare help <option>\" to get more information on that option\n\n"));
127
128         net_common_flags_usage(c, argc, argv);
129         return -1;
130 }
131
132 /***************************************************************************
133 ***************************************************************************/
134
135 static char *get_basepath(TALLOC_CTX *ctx)
136 {
137         char *basepath = talloc_strdup(ctx, lp_usershare_path());
138
139         if (!basepath) {
140                 return NULL;
141         }
142         if ((basepath[0] != '\0') && (basepath[strlen(basepath)-1] == '/')) {
143                 basepath[strlen(basepath)-1] = '\0';
144         }
145         return basepath;
146 }
147
148 /***************************************************************************
149  Delete a single userlevel share.
150 ***************************************************************************/
151
152 static int net_usershare_delete(struct net_context *c, int argc, const char **argv)
153 {
154         char *us_path;
155         char *sharename;
156
157         if (argc != 1 || c->display_usage) {
158                 return net_usershare_delete_usage(c, argc, argv);
159         }
160
161         if ((sharename = strlower_talloc(talloc_tos(), argv[0])) == NULL) {
162                 d_fprintf(stderr, _("strlower_talloc failed\n"));
163                 return -1;
164         }
165
166         if (!validate_net_name(sharename, INVALID_SHARENAME_CHARS, strlen(sharename))) {
167                 d_fprintf(stderr, _("net usershare delete: share name %s contains "
168                         "invalid characters (any of %s)\n"),
169                         sharename, INVALID_SHARENAME_CHARS);
170                 TALLOC_FREE(sharename);
171                 return -1;
172         }
173
174         us_path = talloc_asprintf(talloc_tos(),
175                                 "%s/%s",
176                                 lp_usershare_path(),
177                                 sharename);
178         if (!us_path) {
179                 TALLOC_FREE(sharename);
180                 return -1;
181         }
182
183         if (unlink(us_path) != 0) {
184                 d_fprintf(stderr, _("net usershare delete: unable to remove usershare %s. "
185                         "Error was %s\n"),
186                         us_path, strerror(errno));
187                 TALLOC_FREE(sharename);
188                 return -1;
189         }
190         TALLOC_FREE(sharename);
191         return 0;
192 }
193
194 /***************************************************************************
195  Data structures to handle a list of usershare files.
196 ***************************************************************************/
197
198 struct file_list {
199         struct file_list *next, *prev;
200         const char *pathname;
201 };
202
203 static struct file_list *flist;
204
205 /***************************************************************************
206 ***************************************************************************/
207
208 static int get_share_list(TALLOC_CTX *ctx, const char *wcard, bool only_ours)
209 {
210         SMB_STRUCT_DIR *dp;
211         SMB_STRUCT_DIRENT *de;
212         uid_t myuid = geteuid();
213         struct file_list *fl = NULL;
214         char *basepath = get_basepath(ctx);
215
216         if (!basepath) {
217                 return -1;
218         }
219         dp = sys_opendir(basepath);
220         if (!dp) {
221                 d_fprintf(stderr,
222                         _("get_share_list: cannot open usershare directory %s. "
223                           "Error %s\n"),
224                         basepath, strerror(errno) );
225                 return -1;
226         }
227
228         while((de = sys_readdir(dp)) != 0) {
229                 SMB_STRUCT_STAT sbuf;
230                 char *path;
231                 const char *n = de->d_name;
232
233                 /* Ignore . and .. */
234                 if (*n == '.') {
235                         if ((n[1] == '\0') || (n[1] == '.' && n[2] == '\0')) {
236                                 continue;
237                         }
238                 }
239
240                 if (!validate_net_name(n, INVALID_SHARENAME_CHARS, strlen(n))) {
241                         d_fprintf(stderr,
242                                   _("get_share_list: ignoring bad share "
243                                     "name %s\n"), n);
244                         continue;
245                 }
246                 path = talloc_asprintf(ctx,
247                                         "%s/%s",
248                                         basepath,
249                                         n);
250                 if (!path) {
251                         sys_closedir(dp);
252                         return -1;
253                 }
254
255                 if (sys_lstat(path, &sbuf, false) != 0) {
256                         d_fprintf(stderr,
257                                 _("get_share_list: can't lstat file %s. Error "
258                                   "was %s\n"),
259                                 path, strerror(errno) );
260                         continue;
261                 }
262
263                 if (!S_ISREG(sbuf.st_ex_mode)) {
264                         d_fprintf(stderr,
265                                   _("get_share_list: file %s is not a regular "
266                                     "file. Ignoring.\n"),
267                                 path );
268                         continue;
269                 }
270
271                 if (only_ours && sbuf.st_ex_uid != myuid) {
272                         continue;
273                 }
274
275                 if (!unix_wild_match(wcard, n)) {
276                         continue;
277                 }
278
279                 /* (Finally) - add to list. */
280                 fl = TALLOC_P(ctx, struct file_list);
281                 if (!fl) {
282                         sys_closedir(dp);
283                         return -1;
284                 }
285                 fl->pathname = talloc_strdup(ctx, n);
286                 if (!fl->pathname) {
287                         sys_closedir(dp);
288                         return -1;
289                 }
290
291                 DLIST_ADD(flist, fl);
292         }
293
294         sys_closedir(dp);
295         return 0;
296 }
297
298 enum us_priv_op { US_LIST_OP, US_INFO_OP};
299
300 struct us_priv_info {
301         TALLOC_CTX *ctx;
302         enum us_priv_op op;
303         struct net_context *c;
304 };
305
306 /***************************************************************************
307  Call a function for every share on the list.
308 ***************************************************************************/
309
310 static int process_share_list(int (*fn)(struct file_list *, void *), void *priv)
311 {
312         struct file_list *fl;
313         int ret = 0;
314
315         for (fl = flist; fl; fl = fl->next) {
316                 ret = (*fn)(fl, priv);
317         }
318
319         return ret;
320 }
321
322 /***************************************************************************
323  Info function.
324 ***************************************************************************/
325
326 static int info_fn(struct file_list *fl, void *priv)
327 {
328         SMB_STRUCT_STAT sbuf;
329         char **lines = NULL;
330         struct us_priv_info *pi = (struct us_priv_info *)priv;
331         TALLOC_CTX *ctx = pi->ctx;
332         struct net_context *c = pi->c;
333         int fd = -1;
334         int numlines = 0;
335         struct security_descriptor *psd = NULL;
336         char *basepath;
337         char *sharepath = NULL;
338         char *comment = NULL;
339         char *cp_sharename = NULL;
340         char *acl_str;
341         int num_aces;
342         char sep_str[2];
343         enum usershare_err us_err;
344         bool guest_ok = false;
345
346         sep_str[0] = *lp_winbind_separator();
347         sep_str[1] = '\0';
348
349         basepath = get_basepath(ctx);
350         if (!basepath) {
351                 return -1;
352         }
353         basepath = talloc_asprintf_append(basepath,
354                         "/%s",
355                         fl->pathname);
356         if (!basepath) {
357                 return -1;
358         }
359
360 #ifdef O_NOFOLLOW
361         fd = sys_open(basepath, O_RDONLY|O_NOFOLLOW, 0);
362 #else
363         fd = sys_open(basepath, O_RDONLY, 0);
364 #endif
365
366         if (fd == -1) {
367                 d_fprintf(stderr, _("info_fn: unable to open %s. %s\n"),
368                         basepath, strerror(errno) );
369                 return -1;
370         }
371
372         /* Paranoia... */
373         if (sys_fstat(fd, &sbuf, false) != 0) {
374                 d_fprintf(stderr,
375                         _("info_fn: can't fstat file %s. Error was %s\n"),
376                         basepath, strerror(errno) );
377                 close(fd);
378                 return -1;
379         }
380
381         if (!S_ISREG(sbuf.st_ex_mode)) {
382                 d_fprintf(stderr,
383                         _("info_fn: file %s is not a regular file. Ignoring.\n"),
384                         basepath );
385                 close(fd);
386                 return -1;
387         }
388
389         lines = fd_lines_load(fd, &numlines, 10240, NULL);
390         close(fd);
391
392         if (lines == NULL) {
393                 return -1;
394         }
395
396         /* Ensure it's well formed. */
397         us_err = parse_usershare_file(ctx, &sbuf, fl->pathname, -1, lines, numlines,
398                                 &sharepath,
399                                 &comment,
400                                 &cp_sharename,
401                                 &psd,
402                                 &guest_ok);
403
404         TALLOC_FREE(lines);
405
406         if (us_err != USERSHARE_OK) {
407                 d_fprintf(stderr,
408                         _("info_fn: file %s is not a well formed usershare "
409                           "file.\n"),
410                         basepath );
411                 d_fprintf(stderr, _("info_fn: Error was %s.\n"),
412                         get_us_error_code(us_err) );
413                 return -1;
414         }
415
416         acl_str = talloc_strdup(ctx, "usershare_acl=");
417         if (!acl_str) {
418                 return -1;
419         }
420
421         for (num_aces = 0; num_aces < psd->dacl->num_aces; num_aces++) {
422                 const char *domain;
423                 const char *name;
424                 NTSTATUS ntstatus;
425
426                 ntstatus = net_lookup_name_from_sid(c, ctx,
427                                                     &psd->dacl->aces[num_aces].trustee,
428                                                     &domain, &name);
429
430                 if (NT_STATUS_IS_OK(ntstatus)) {
431                         if (domain && *domain) {
432                                 acl_str = talloc_asprintf_append(acl_str,
433                                                 "%s%s",
434                                                 domain,
435                                                 sep_str);
436                                 if (!acl_str) {
437                                         return -1;
438                                 }
439                         }
440                         acl_str = talloc_asprintf_append(acl_str,
441                                                 "%s",
442                                                 name);
443                         if (!acl_str) {
444                                 return -1;
445                         }
446
447                 } else {
448                         fstring sidstr;
449                         sid_to_fstring(sidstr,
450                                        &psd->dacl->aces[num_aces].trustee);
451                         acl_str = talloc_asprintf_append(acl_str,
452                                                 "%s",
453                                                 sidstr);
454                         if (!acl_str) {
455                                 return -1;
456                         }
457                 }
458                 acl_str = talloc_asprintf_append(acl_str, ":");
459                 if (!acl_str) {
460                         return -1;
461                 }
462
463                 if (psd->dacl->aces[num_aces].type == SEC_ACE_TYPE_ACCESS_DENIED) {
464                         acl_str = talloc_asprintf_append(acl_str, "D,");
465                         if (!acl_str) {
466                                 return -1;
467                         }
468                 } else {
469                         if (psd->dacl->aces[num_aces].access_mask & GENERIC_ALL_ACCESS) {
470                                 acl_str = talloc_asprintf_append(acl_str, "F,");
471                         } else {
472                                 acl_str = talloc_asprintf_append(acl_str, "R,");
473                         }
474                         if (!acl_str) {
475                                 return -1;
476                         }
477                 }
478         }
479
480         /* NOTE: This is smb.conf-like output. Do not translate. */
481         if (pi->op == US_INFO_OP) {
482                 d_printf("[%s]\n", cp_sharename );
483                 d_printf("path=%s\n", sharepath );
484                 d_printf("comment=%s\n", comment);
485                 d_printf("%s\n", acl_str);
486                 d_printf("guest_ok=%c\n\n", guest_ok ? 'y' : 'n');
487         } else if (pi->op == US_LIST_OP) {
488                 d_printf("%s\n", cp_sharename);
489         }
490
491         return 0;
492 }
493
494 /***************************************************************************
495  Print out info (internal detail) on userlevel shares.
496 ***************************************************************************/
497
498 static int net_usershare_info(struct net_context *c, int argc, const char **argv)
499 {
500         fstring wcard;
501         bool only_ours = true;
502         int ret = -1;
503         struct us_priv_info pi;
504         TALLOC_CTX *ctx;
505
506         fstrcpy(wcard, "*");
507
508         if (c->display_usage)
509                 return net_usershare_info_usage(c, argc, argv);
510
511         if (c->opt_long_list_entries) {
512                 only_ours = false;
513         }
514
515         switch (argc) {
516                 case 0:
517                         break;
518                 case 1:
519                         fstrcpy(wcard, argv[0]);
520                         break;
521                 default:
522                         return net_usershare_info_usage(c, argc, argv);
523         }
524
525         strlower_m(wcard);
526
527         ctx = talloc_init("share_info");
528         ret = get_share_list(ctx, wcard, only_ours);
529         if (ret) {
530                 return ret;
531         }
532
533         pi.ctx = ctx;
534         pi.op = US_INFO_OP;
535         pi.c = c;
536
537         ret = process_share_list(info_fn, &pi);
538         talloc_destroy(ctx);
539         return ret;
540 }
541
542 /***************************************************************************
543  Count the current total number of usershares.
544 ***************************************************************************/
545
546 static int count_num_usershares(void)
547 {
548         SMB_STRUCT_DIR *dp;
549         SMB_STRUCT_DIRENT *de;
550         int num_usershares = 0;
551         TALLOC_CTX *ctx = talloc_tos();
552         char *basepath = get_basepath(ctx);
553
554         if (!basepath) {
555                 return -1;
556         }
557
558         dp = sys_opendir(basepath);
559         if (!dp) {
560                 d_fprintf(stderr,
561                         _("count_num_usershares: cannot open usershare "
562                           "directory %s. Error %s\n"),
563                         basepath, strerror(errno) );
564                 return -1;
565         }
566
567         while((de = sys_readdir(dp)) != 0) {
568                 SMB_STRUCT_STAT sbuf;
569                 char *path;
570                 const char *n = de->d_name;
571
572                 /* Ignore . and .. */
573                 if (*n == '.') {
574                         if ((n[1] == '\0') || (n[1] == '.' && n[2] == '\0')) {
575                                 continue;
576                         }
577                 }
578
579                 if (!validate_net_name(n, INVALID_SHARENAME_CHARS, strlen(n))) {
580                         d_fprintf(stderr,
581                                   _("count_num_usershares: ignoring bad share "
582                                     "name %s\n"), n);
583                         continue;
584                 }
585                 path = talloc_asprintf(ctx,
586                                 "%s/%s",
587                                 basepath,
588                                 n);
589                 if (!path) {
590                         sys_closedir(dp);
591                         return -1;
592                 }
593
594                 if (sys_lstat(path, &sbuf, false) != 0) {
595                         d_fprintf(stderr,
596                                 _("count_num_usershares: can't lstat file %s. "
597                                   "Error was %s\n"),
598                                 path, strerror(errno) );
599                         continue;
600                 }
601
602                 if (!S_ISREG(sbuf.st_ex_mode)) {
603                         d_fprintf(stderr,
604                                 _("count_num_usershares: file %s is not a "
605                                   "regular file. Ignoring.\n"),
606                                 path );
607                         continue;
608                 }
609                 num_usershares++;
610         }
611
612         sys_closedir(dp);
613         return num_usershares;
614 }
615
616 /***************************************************************************
617  Add a single userlevel share.
618 ***************************************************************************/
619
620 static int net_usershare_add(struct net_context *c, int argc, const char **argv)
621 {
622         TALLOC_CTX *ctx = talloc_stackframe();
623         SMB_STRUCT_STAT sbuf;
624         SMB_STRUCT_STAT lsbuf;
625         char *sharename;
626         const char *cp_sharename;
627         char *full_path;
628         char *full_path_tmp;
629         const char *us_path;
630         const char *us_comment;
631         const char *arg_acl;
632         char *us_acl;
633         char *file_img;
634         int num_aces = 0;
635         int i;
636         int tmpfd;
637         const char *pacl;
638         size_t to_write;
639         uid_t myeuid = geteuid();
640         bool guest_ok = false;
641         int num_usershares;
642
643         us_comment = "";
644         arg_acl = "S-1-1-0:R";
645
646         if (c->display_usage)
647                 return net_usershare_add_usage(c, argc, argv);
648
649         switch (argc) {
650                 case 0:
651                 case 1:
652                 default:
653                         return net_usershare_add_usage(c, argc, argv);
654                 case 2:
655                         cp_sharename = argv[0];
656                         sharename = strlower_talloc(ctx, argv[0]);
657                         us_path = argv[1];
658                         break;
659                 case 3:
660                         cp_sharename = argv[0];
661                         sharename = strlower_talloc(ctx, argv[0]);
662                         us_path = argv[1];
663                         us_comment = argv[2];
664                         break;
665                 case 4:
666                         cp_sharename = argv[0];
667                         sharename = strlower_talloc(ctx, argv[0]);
668                         us_path = argv[1];
669                         us_comment = argv[2];
670                         arg_acl = argv[3];
671                         break;
672                 case 5:
673                         cp_sharename = argv[0];
674                         sharename = strlower_talloc(ctx, argv[0]);
675                         us_path = argv[1];
676                         us_comment = argv[2];
677                         arg_acl = argv[3];
678                         if (strlen(arg_acl) == 0) {
679                                 arg_acl = "S-1-1-0:R";
680                         }
681                         if (!strnequal(argv[4], "guest_ok=", 9)) {
682                                 TALLOC_FREE(ctx);
683                                 return net_usershare_add_usage(c, argc, argv);
684                         }
685                         switch (argv[4][9]) {
686                                 case 'y':
687                                 case 'Y':
688                                         guest_ok = true;
689                                         break;
690                                 case 'n':
691                                 case 'N':
692                                         guest_ok = false;
693                                         break;
694                                 default:
695                                         TALLOC_FREE(ctx);
696                                         return net_usershare_add_usage(c, argc, argv);
697                         }
698                         break;
699         }
700
701         /* Ensure we're under the "usershare max shares" number. Advisory only. */
702         num_usershares = count_num_usershares();
703         if (num_usershares >= lp_usershare_max_shares()) {
704                 d_fprintf(stderr,
705                         _("net usershare add: maximum number of allowed "
706                           "usershares (%d) reached\n"),
707                         lp_usershare_max_shares() );
708                 TALLOC_FREE(ctx);
709                 return -1;
710         }
711
712         if (!validate_net_name(sharename, INVALID_SHARENAME_CHARS, strlen(sharename))) {
713                 d_fprintf(stderr, _("net usershare add: share name %s contains "
714                         "invalid characters (any of %s)\n"),
715                         sharename, INVALID_SHARENAME_CHARS);
716                 TALLOC_FREE(ctx);
717                 return -1;
718         }
719
720         /* Disallow shares the same as users. */
721         if (getpwnam(sharename)) {
722                 d_fprintf(stderr,
723                         _("net usershare add: share name %s is already a valid "
724                           "system user name\n"),
725                         sharename );
726                 TALLOC_FREE(ctx);
727                 return -1;
728         }
729
730         /* Construct the full path for the usershare file. */
731         full_path = get_basepath(ctx);
732         if (!full_path) {
733                 TALLOC_FREE(ctx);
734                 return -1;
735         }
736         full_path_tmp = talloc_asprintf(ctx,
737                         "%s/:tmpXXXXXX",
738                         full_path);
739         if (!full_path_tmp) {
740                 TALLOC_FREE(ctx);
741                 return -1;
742         }
743
744         full_path = talloc_asprintf_append(full_path,
745                                         "/%s",
746                                         sharename);
747         if (!full_path) {
748                 TALLOC_FREE(ctx);
749                 return -1;
750         }
751
752         /* The path *must* be absolute. */
753         if (us_path[0] != '/') {
754                 d_fprintf(stderr,
755                         _("net usershare add: path %s is not an absolute "
756                           "path.\n"),
757                         us_path);
758                 TALLOC_FREE(ctx);
759                 return -1;
760         }
761
762         /* Check the directory to be shared exists. */
763         if (sys_stat(us_path, &sbuf, false) != 0) {
764                 d_fprintf(stderr,
765                         _("net usershare add: cannot stat path %s to ensure "
766                           "this is a directory. Error was %s\n"),
767                         us_path, strerror(errno) );
768                 TALLOC_FREE(ctx);
769                 return -1;
770         }
771
772         if (!S_ISDIR(sbuf.st_ex_mode)) {
773                 d_fprintf(stderr,
774                         _("net usershare add: path %s is not a directory.\n"),
775                         us_path );
776                 TALLOC_FREE(ctx);
777                 return -1;
778         }
779
780         /* If we're not root, check if we're restricted to sharing out directories
781            that we own only. */
782
783         if ((myeuid != 0) && lp_usershare_owner_only() && (myeuid != sbuf.st_ex_uid)) {
784                 d_fprintf(stderr, _("net usershare add: cannot share path %s as "
785                         "we are restricted to only sharing directories we own.\n"
786                         "\tAsk the administrator to add the line \"usershare owner only = false\" \n"
787                         "\tto the [global] section of the smb.conf to allow this.\n"),
788                         us_path );
789                 TALLOC_FREE(ctx);
790                 return -1;
791         }
792
793         /* No validation needed on comment. Now go through and validate the
794            acl string. Convert names to SID's as needed. Then run it through
795            parse_usershare_acl to ensure it's valid. */
796
797         /* Start off the string we'll append to. */
798         us_acl = talloc_strdup(ctx, "");
799         if (!us_acl) {
800                 TALLOC_FREE(ctx);
801                 return -1;
802         }
803
804         pacl = arg_acl;
805         num_aces = 1;
806
807         /* Add the number of ',' characters to get the number of aces. */
808         num_aces += count_chars(pacl,',');
809
810         for (i = 0; i < num_aces; i++) {
811                 struct dom_sid sid;
812                 const char *pcolon = strchr_m(pacl, ':');
813                 const char *name;
814
815                 if (pcolon == NULL) {
816                         d_fprintf(stderr,
817                                 _("net usershare add: malformed acl %s "
818                                   "(missing ':').\n"),
819                                 pacl );
820                         TALLOC_FREE(ctx);
821                         return -1;
822                 }
823
824                 switch(pcolon[1]) {
825                         case 'f':
826                         case 'F':
827                         case 'd':
828                         case 'r':
829                         case 'R':
830                                 break;
831                         default:
832                                 d_fprintf(stderr,
833                                         _("net usershare add: malformed acl %s "
834                                           "(access control must be 'r', 'f', "
835                                           "or 'd')\n"),
836                                         pacl );
837                                 TALLOC_FREE(ctx);
838                                 return -1;
839                 }
840
841                 if (pcolon[2] != ',' && pcolon[2] != '\0') {
842                         d_fprintf(stderr,
843                                 _("net usershare add: malformed terminating "
844                                   "character for acl %s\n"),
845                                 pacl );
846                         TALLOC_FREE(ctx);
847                         return -1;
848                 }
849
850                 /* Get the name */
851                 if ((name = talloc_strndup(ctx, pacl, pcolon - pacl)) == NULL) {
852                         d_fprintf(stderr, _("talloc_strndup failed\n"));
853                         TALLOC_FREE(ctx);
854                         return -1;
855                 }
856                 if (!string_to_sid(&sid, name)) {
857                         /* Convert to a SID */
858                         NTSTATUS ntstatus = net_lookup_sid_from_name(c, ctx, name, &sid);
859                         if (!NT_STATUS_IS_OK(ntstatus)) {
860                                 d_fprintf(stderr,
861                                         _("net usershare add: cannot convert "
862                                           "name \"%s\" to a SID. %s."),
863                                         name, get_friendly_nt_error_msg(ntstatus) );
864                                 if (NT_STATUS_EQUAL(ntstatus, NT_STATUS_CONNECTION_REFUSED)) {
865                                         d_fprintf(stderr,
866                                             _(" Maybe smbd is not running.\n"));
867                                 } else {
868                                         d_fprintf(stderr, "\n");
869                                 }
870                                 TALLOC_FREE(ctx);
871                                 return -1;
872                         }
873                 }
874                 us_acl = talloc_asprintf_append(
875                         us_acl, "%s:%c,", sid_string_tos(&sid), pcolon[1]);
876
877                 /* Move to the next ACL entry. */
878                 if (pcolon[2] == ',') {
879                         pacl = &pcolon[3];
880                 }
881         }
882
883         /* Remove the last ',' */
884         us_acl[strlen(us_acl)-1] = '\0';
885
886         if (guest_ok && !lp_usershare_allow_guests()) {
887                 d_fprintf(stderr, _("net usershare add: guest_ok=y requested "
888                         "but the \"usershare allow guests\" parameter is not "
889                         "enabled by this server.\n"));
890                 TALLOC_FREE(ctx);
891                 return -1;
892         }
893
894         /* Create a temporary filename for this share. */
895         tmpfd = mkstemp(full_path_tmp);
896
897         if (tmpfd == -1) {
898                 d_fprintf(stderr,
899                           _("net usershare add: cannot create tmp file %s\n"),
900                           full_path_tmp );
901                 TALLOC_FREE(ctx);
902                 return -1;
903         }
904
905         /* Ensure we opened the file we thought we did. */
906         if (sys_lstat(full_path_tmp, &lsbuf, false) != 0) {
907                 d_fprintf(stderr,
908                           _("net usershare add: cannot lstat tmp file %s\n"),
909                           full_path_tmp );
910                 TALLOC_FREE(ctx);
911                 close(tmpfd);
912                 return -1;
913         }
914
915         /* Check this is the same as the file we opened. */
916         if (sys_fstat(tmpfd, &sbuf, false) != 0) {
917                 d_fprintf(stderr,
918                           _("net usershare add: cannot fstat tmp file %s\n"),
919                           full_path_tmp );
920                 TALLOC_FREE(ctx);
921                 close(tmpfd);
922                 return -1;
923         }
924
925         if (!S_ISREG(sbuf.st_ex_mode) || sbuf.st_ex_dev != lsbuf.st_ex_dev || sbuf.st_ex_ino != lsbuf.st_ex_ino) {
926                 d_fprintf(stderr,
927                           _("net usershare add: tmp file %s is not a regular "
928                             "file ?\n"),
929                           full_path_tmp );
930                 TALLOC_FREE(ctx);
931                 close(tmpfd);
932                 return -1;
933         }
934
935         if (fchmod(tmpfd, 0644) == -1) {
936                 d_fprintf(stderr,
937                           _("net usershare add: failed to fchmod tmp file %s "
938                             "to 0644n"),
939                           full_path_tmp );
940                 TALLOC_FREE(ctx);
941                 close(tmpfd);
942                 return -1;
943         }
944
945         /* Create the in-memory image of the file. */
946         file_img = talloc_strdup(ctx, "#VERSION 2\npath=");
947         file_img = talloc_asprintf_append(file_img,
948                         "%s\ncomment=%s\nusershare_acl=%s\n"
949                         "guest_ok=%c\nsharename=%s\n",
950                         us_path,
951                         us_comment,
952                         us_acl,
953                         guest_ok ? 'y' : 'n',
954                         cp_sharename);
955
956         to_write = strlen(file_img);
957
958         if (write(tmpfd, file_img, to_write) != to_write) {
959                 d_fprintf(stderr,
960                         _("net usershare add: failed to write %u bytes to "
961                           "file %s. Error was %s\n"),
962                         (unsigned int)to_write, full_path_tmp, strerror(errno));
963                 unlink(full_path_tmp);
964                 TALLOC_FREE(ctx);
965                 close(tmpfd);
966                 return -1;
967         }
968
969         /* Attempt to replace any existing share by this name. */
970         if (rename(full_path_tmp, full_path) != 0) {
971                 unlink(full_path_tmp);
972                 d_fprintf(stderr,
973                         _("net usershare add: failed to add share %s. Error "
974                           "was %s\n"),
975                         sharename, strerror(errno));
976                 TALLOC_FREE(ctx);
977                 close(tmpfd);
978                 return -1;
979         }
980
981         close(tmpfd);
982
983         if (c->opt_long_list_entries) {
984                 const char *my_argv[2];
985                 my_argv[0] = sharename;
986                 my_argv[1] = NULL;
987                 net_usershare_info(c, 1, my_argv);
988         }
989
990         TALLOC_FREE(ctx);
991         return 0;
992 }
993
994 #if 0
995 /***************************************************************************
996  List function.
997 ***************************************************************************/
998
999 static int list_fn(struct file_list *fl, void *priv)
1000 {
1001         d_printf("%s\n", fl->pathname);
1002         return 0;
1003 }
1004 #endif
1005
1006 /***************************************************************************
1007  List userlevel shares.
1008 ***************************************************************************/
1009
1010 static int net_usershare_list(struct net_context *c, int argc,
1011                               const char **argv)
1012 {
1013         fstring wcard;
1014         bool only_ours = true;
1015         int ret = -1;
1016         struct us_priv_info pi;
1017         TALLOC_CTX *ctx;
1018
1019         fstrcpy(wcard, "*");
1020
1021         if (c->display_usage)
1022                 return net_usershare_list_usage(c, argc, argv);
1023
1024         if (c->opt_long_list_entries) {
1025                 only_ours = false;
1026         }
1027
1028         switch (argc) {
1029                 case 0:
1030                         break;
1031                 case 1:
1032                         fstrcpy(wcard, argv[0]);
1033                         break;
1034                 default:
1035                         return net_usershare_list_usage(c, argc, argv);
1036         }
1037
1038         strlower_m(wcard);
1039
1040         ctx = talloc_init("share_list");
1041         ret = get_share_list(ctx, wcard, only_ours);
1042         if (ret) {
1043                 return ret;
1044         }
1045
1046         pi.ctx = ctx;
1047         pi.op = US_LIST_OP;
1048         pi.c = c;
1049
1050         ret = process_share_list(info_fn, &pi);
1051         talloc_destroy(ctx);
1052         return ret;
1053 }
1054
1055 /***************************************************************************
1056  Entry-point for all the USERSHARE functions.
1057 ***************************************************************************/
1058
1059 int net_usershare(struct net_context *c, int argc, const char **argv)
1060 {
1061         SMB_STRUCT_DIR *dp;
1062
1063         struct functable func[] = {
1064                 {
1065                         "add",
1066                         net_usershare_add,
1067                         NET_TRANSPORT_LOCAL,
1068                         N_("Add/modify user defined share"),
1069                         N_("net usershare add\n"
1070                            "    Add/modify user defined share")
1071                 },
1072                 {
1073                         "delete",
1074                         net_usershare_delete,
1075                         NET_TRANSPORT_LOCAL,
1076                         N_("Delete user defined share"),
1077                         N_("net usershare delete\n"
1078                            "    Delete user defined share")
1079                 },
1080                 {
1081                         "info",
1082                         net_usershare_info,
1083                         NET_TRANSPORT_LOCAL,
1084                         N_("Display information about a user defined share"),
1085                         N_("net usershare info\n"
1086                            "    Display information about a user defined share")
1087                 },
1088                 {
1089                         "list",
1090                         net_usershare_list,
1091                         NET_TRANSPORT_LOCAL,
1092                         N_("List user defined shares"),
1093                         N_("net usershare list\n"
1094                            "    List user defined shares")
1095                 },
1096                 {NULL, NULL, 0, NULL, NULL}
1097         };
1098
1099         if (lp_usershare_max_shares() == 0) {
1100                 d_fprintf(stderr,
1101                           _("net usershare: usershares are currently "
1102                             "disabled\n"));
1103                 return -1;
1104         }
1105
1106         dp = sys_opendir(lp_usershare_path());
1107         if (!dp) {
1108                 int err = errno;
1109                 d_fprintf(stderr,
1110                         _("net usershare: cannot open usershare directory %s. "
1111                           "Error %s\n"),
1112                         lp_usershare_path(), strerror(err) );
1113                 if (err == EACCES) {
1114                         d_fprintf(stderr,
1115                                 _("You do not have permission to create a "
1116                                 "usershare. Ask your administrator to grant "
1117                                 "you permissions to create a share.\n"));
1118                 } else if (err == ENOENT) {
1119                         d_fprintf(stderr,
1120                                 _("Please ask your system administrator to "
1121                                   "enable user sharing.\n"));
1122                 }
1123                 return -1;
1124         }
1125         sys_closedir(dp);
1126
1127         return net_run_function(c, argc, argv, "net usershare", func);
1128 }