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