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