forked from fish-shell/fish-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
env_universal_common.cpp
1691 lines (1472 loc) · 51.1 KB
/
env_universal_common.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
\file env_universal_common.c
The utility library for universal variables. Used both by the
client library and by the daemon.
*/
#include "config.h"
#include "env_universal_common.h"
#include <fcntl.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pwd.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include "fallback.h"
#include "util.h"
#include "common.h"
#include "wutil.h"
#include "utf8.h"
#include "path.h"
#include "iothread.h"
#if __APPLE__
#define FISH_NOTIFYD_AVAILABLE 1
#include <notify.h>
#endif
// NAME_MAX is not defined on Solaris and suggests the use of pathconf()
// There is no obvious sensible pathconf() for shared memory and _XPG_NAME_MAX
// seems a reasonable choice.
#if !defined(NAME_MAX) && defined(_XOPEN_NAME_MAX)
#define NAME_MAX _XOPEN_NAME_MAX
#endif
/**
The set command
*/
#define SET_STR L"SET"
/**
The set_export command
*/
#define SET_EXPORT_STR L"SET_EXPORT"
/**
Non-wide version of the set command
*/
#define SET_MBS "SET"
/**
Non-wide version of the set_export command
*/
#define SET_EXPORT_MBS "SET_EXPORT"
/**
Error message
*/
#define PARSE_ERR L"Unable to parse universal variable message: '%ls'"
/** Small note about not editing ~/.fishd manually. Inserted at the top of all .fishd files. */
#define SAVE_MSG "# This file is automatically generated by the fish.\n# Do NOT edit it directly, your changes will be overwritten.\n"
static wcstring fishd_get_config();
static wcstring get_machine_identifier();
static bool get_hostname_identifier(wcstring *result);
static wcstring vars_filename_in_directory(const wcstring &wdir)
{
if (wdir.empty())
return L"";
wcstring result = wdir;
result.append(L"/fishd.");
result.append(get_machine_identifier());
return result;
}
static const wcstring &default_vars_path()
{
static wcstring cached_result = vars_filename_in_directory(fishd_get_config());
return cached_result;
}
/**
Check, and create if necessary, a secure runtime path
Derived from tmux.c in tmux (http://tmux.sourceforge.net/)
*/
static int check_runtime_path(const char * path)
{
/*
* Copyright (c) 2007 Nicholas Marriott <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
struct stat statpath;
u_int uid = geteuid();
if (mkdir(path, S_IRWXU) != 0 && errno != EEXIST)
return errno;
if (lstat(path, &statpath) != 0)
return errno;
if (!S_ISDIR(statpath.st_mode)
|| statpath.st_uid != uid
|| (statpath.st_mode & (S_IRWXG|S_IRWXO)) != 0)
return EACCES;
return 0;
}
/** Return the path of an appropriate runtime data directory */
static wcstring get_runtime_path()
{
wcstring result;
const char *dir = getenv("XDG_RUNTIME_DIR");
if (dir != NULL)
{
result = str2wcstring(dir);
}
else
{
const char *uname = getenv("USER");
if (uname == NULL)
{
const struct passwd *pw = getpwuid(getuid());
uname = pw->pw_name;
}
// /tmp/fish.user
std::string tmpdir = "/tmp/fish.";
tmpdir.append(uname);
if (check_runtime_path(tmpdir.c_str()) != 0)
{
debug(0, L"Runtime path not available. Try deleting the directory %s and restarting fish.", tmpdir.c_str());
}
else
{
result = str2wcstring(tmpdir);
}
}
return result;
}
/* Returns a "variables" file in the appropriate runtime directory. This is called infrequently and so does not need to be cached. */
static wcstring default_named_pipe_path()
{
// Note that vars_filename_in_directory returns empty string when passed the empty string
return vars_filename_in_directory(get_runtime_path());
}
/**
Test if the message msg contains the command cmd
*/
static bool match(const wchar_t *msg, const wchar_t *cmd)
{
size_t len = wcslen(cmd);
if (wcsncasecmp(msg, cmd, len) != 0)
return false;
if (msg[len] && msg[len]!= L' ' && msg[len] != L'\t')
return false;
return true;
}
static void report_error(int err_code, const wchar_t *err_format, ...)
{
va_list va;
va_start(va, err_format);
const wcstring err_text = vformat_string(err_format, va);
va_end(va);
if (! err_text.empty())
{
fwprintf(stderr, L"%ls: ", err_text.c_str());
}
fwprintf(stderr, L"%s\n", strerror(err_code));
}
/* The universal variable format has some funny escaping requirements; here we try to be safe */
static bool is_universal_safe_to_encode_directly(wchar_t c)
{
if (c < 32 || c > 128)
return false;
return iswalnum(c) || wcschr(L"/_", c);
}
/**
Escape specified string
*/
static wcstring full_escape(const wchar_t *in)
{
wcstring out;
for (; *in; in++)
{
wchar_t c = *in;
if (is_universal_safe_to_encode_directly(c))
{
out.push_back(c);
}
else if (c <= (wchar_t)ASCII_MAX)
{
// See #1225 for discussion of use of ASCII_MAX here
append_format(out, L"\\x%.2x", c);
}
else if (c < 65536)
{
append_format(out, L"\\u%.4x", c);
}
else
{
append_format(out, L"\\U%.8x", c);
}
}
return out;
}
/* Converts input to UTF-8 and appends it to receiver, using storage as temp storage */
static bool append_utf8(const wcstring &input, std::string *receiver, std::string *storage)
{
bool result = false;
if (wchar_to_utf8_string(input, storage))
{
receiver->append(*storage);
result = true;
}
return result;
}
/* Creates a file entry like "SET fish_color_cwd:FF0". Appends the result to *result (as UTF8). Returns true on success. storage may be used for temporary storage, to avoid allocations */
static bool append_file_entry(fish_message_type_t type, const wcstring &key_in, const wcstring &val_in, std::string *result, std::string *storage)
{
assert(storage != NULL);
assert(result != NULL);
// Record the length on entry, in case we need to back up
bool success = true;
const size_t result_length_on_entry = result->size();
// Append header like "SET "
result->append(type==SET ? SET_MBS : SET_EXPORT_MBS);
result->push_back(' ');
// Append variable name like "fish_color_cwd"
if (wcsvarname(key_in.c_str()))
{
debug(0, L"Illegal variable name: '%ls'", key_in.c_str());
success = false;
}
if (success && ! append_utf8(key_in, result, storage))
{
debug(0, L"Could not convert %ls to narrow character string", key_in.c_str());
success = false;
}
// Append ":"
if (success)
{
result->push_back(':');
}
// Append value
if (success && ! append_utf8(full_escape(val_in.c_str()), result, storage))
{
debug(0, L"Could not convert %ls to narrow character string", val_in.c_str());
success = false;
}
// Append newline
if (success)
{
result->push_back('\n');
}
// Don't modify result on failure. It's sufficient to simply resize it since all we ever did was append to it.
if (! success)
{
result->resize(result_length_on_entry);
}
return success;
}
env_universal_t::env_universal_t(const wcstring &path) : explicit_vars_path(path), tried_renaming(false), last_read_file(kInvalidFileID)
{
VOMIT_ON_FAILURE(pthread_mutex_init(&lock, NULL));
}
env_universal_t::~env_universal_t()
{
pthread_mutex_destroy(&lock);
}
env_var_t env_universal_t::get(const wcstring &name) const
{
env_var_t result = env_var_t::missing_var();
var_table_t::const_iterator where = vars.find(name);
if (where != vars.end())
{
result = where->second.val;
}
return result;
}
bool env_universal_t::get_export(const wcstring &name) const
{
bool result = false;
var_table_t::const_iterator where = vars.find(name);
if (where != vars.end())
{
result = where->second.exportv;
}
return result;
}
void env_universal_t::set_internal(const wcstring &key, const wcstring &val, bool exportv, bool overwrite)
{
ASSERT_IS_LOCKED(lock);
if (! overwrite && this->modified.find(key) != this->modified.end())
{
/* This value has been modified and we're not overwriting it. Skip it. */
return;
}
var_entry_t *entry = &vars[key];
if (entry->exportv != exportv || entry->val != val)
{
entry->val = val;
entry->exportv = exportv;
/* If we are overwriting, then this is now modified */
if (overwrite)
{
this->modified.insert(key);
}
}
}
void env_universal_t::set(const wcstring &key, const wcstring &val, bool exportv)
{
scoped_lock locker(lock);
this->set_internal(key, val, exportv, true /* overwrite */);
}
bool env_universal_t::remove_internal(const wcstring &key)
{
ASSERT_IS_LOCKED(lock);
size_t erased = this->vars.erase(key);
if (erased > 0)
{
this->modified.insert(key);
}
return erased > 0;
}
bool env_universal_t::remove(const wcstring &key)
{
scoped_lock locker(lock);
return this->remove_internal(key);
}
wcstring_list_t env_universal_t::get_names(bool show_exported, bool show_unexported) const
{
wcstring_list_t result;
scoped_lock locker(lock);
var_table_t::const_iterator iter;
for (iter = vars.begin(); iter != vars.end(); ++iter)
{
const wcstring &key = iter->first;
const var_entry_t &e = iter->second;
if ((e.exportv && show_exported) || (! e.exportv && show_unexported))
{
result.push_back(key);
}
}
return result;
}
/* Given a variable table, generate callbacks representing the difference between our vars and the new vars */
void env_universal_t::generate_callbacks(const var_table_t &new_vars, callback_data_list_t *callbacks) const
{
assert(callbacks != NULL);
/* Construct callbacks for erased values */
for (var_table_t::const_iterator iter = this->vars.begin(); iter != this->vars.end(); ++iter)
{
const wcstring &key = iter->first;
/* Skip modified values */
if (this->modified.find(key) != this->modified.end())
{
continue;
}
/* If the value is not present in new_vars, it has been erased */
if (new_vars.find(key) == new_vars.end())
{
callbacks->push_back(callback_data_t(ERASE, key, L""));
}
}
/* Construct callbacks for newly inserted or changed values */
for (var_table_t::const_iterator iter = new_vars.begin(); iter != new_vars.end(); ++iter)
{
const wcstring &key = iter->first;
/* Skip modified values */
if (this->modified.find(key) != this->modified.end())
{
continue;
}
/* See if the value has changed */
const var_entry_t &new_entry = iter->second;
var_table_t::const_iterator existing = this->vars.find(key);
if (existing == this->vars.end() || existing->second.exportv != new_entry.exportv || existing->second.val != new_entry.val)
{
/* Value has changed */
callbacks->push_back(callback_data_t(new_entry.exportv ? SET_EXPORT : SET, key, new_entry.val));
}
}
}
void env_universal_t::acquire_variables(var_table_t *vars_to_acquire)
{
/* Copy modified values from existing vars to vars_to_acquire */
for (std::set<wcstring>::iterator iter = this->modified.begin(); iter != this->modified.end(); ++iter)
{
const wcstring &key = *iter;
var_table_t::iterator src_iter = this->vars.find(key);
if (src_iter == this->vars.end())
{
/* The value has been deleted. */
vars_to_acquire->erase(key);
}
else
{
/* The value has been modified. Copy it over. Note we can destructively modify the source entry in vars since we are about to get rid of this->vars entirely. */
var_entry_t &src = src_iter->second;
var_entry_t &dst = (*vars_to_acquire)[key];
dst.val.swap(src.val);
dst.exportv = src.exportv;
}
}
/* We have constructed all the callbacks and updated vars_to_acquire. Acquire it! */
this->vars.swap(*vars_to_acquire);
}
void env_universal_t::load_from_fd(int fd, callback_data_list_t *callbacks)
{
ASSERT_IS_LOCKED(lock);
assert(fd >= 0);
/* Get the dev / inode */
const file_id_t current_file = file_id_for_fd(fd);
if (current_file == last_read_file)
{
UNIVERSAL_LOG("Sync elided based on fstat()");
}
else
{
/* Read a variables table from the file. */
var_table_t new_vars = this->read_message_internal(fd);
/* Announce changes */
if (callbacks != NULL)
{
this->generate_callbacks(new_vars, callbacks);
}
/* Acquire the new variables */
this->acquire_variables(&new_vars);
last_read_file = current_file;
}
}
bool env_universal_t::load_from_path(const wcstring &path, callback_data_list_t *callbacks)
{
ASSERT_IS_LOCKED(lock);
/* Check to see if the file is unchanged. We do this again in load_from_fd, but this avoids opening the file unnecessarily. */
if (last_read_file != kInvalidFileID && file_id_for_path(path) == last_read_file)
{
UNIVERSAL_LOG("Sync elided based on fast stat()");
return true;
}
bool result = false;
int fd = wopen_cloexec(path, O_RDONLY);
if (fd >= 0)
{
UNIVERSAL_LOG("Reading from file");
this->load_from_fd(fd, callbacks);
close(fd);
result = true;
}
return result;
}
/* Writes our state to the fd. path is provided only for error reporting */
bool env_universal_t::write_to_fd(int fd, const wcstring &path)
{
ASSERT_IS_LOCKED(lock);
assert(fd >= 0);
bool success = true;
// Stuff we output to fd
std::string contents;
// Temporary storage
std::string storage;
// Write the save message. If this fails, we don't bother complaining.
write_loop(fd, SAVE_MSG, strlen(SAVE_MSG));
var_table_t::const_iterator iter = vars.begin();
while (iter != vars.end())
{
// Append the entry. Note that append_file_entry may fail, but that only affects one variable; soldier on.
const wcstring &key = iter->first;
const var_entry_t &entry = iter->second;
append_file_entry(entry.exportv ? SET_EXPORT : SET, key, entry.val, &contents, &storage);
// Go to next
++iter;
// Flush if this is the last iteration or we exceed a page
if (iter == vars.end() || contents.size() >= 4096)
{
if (write_loop(fd, contents.data(), contents.size()) < 0)
{
int err = errno;
report_error(err, L"Unable to write to universal variables file '%ls'", path.c_str());
success = false;
break;
}
contents.clear();
}
}
/* Since we just wrote out this file, it matches our internal state; pretend we read from it */
this->last_read_file = file_id_for_fd(fd);
/* We don't close the file */
return success;
}
bool env_universal_t::move_new_vars_file_into_place(const wcstring &src, const wcstring &dst)
{
int ret = wrename(src, dst);
if (ret != 0)
{
int err = errno;
report_error(err, L"Unable to rename file from '%ls' to '%ls'", src.c_str(), dst.c_str());
}
return ret == 0;
}
static wcstring fishd_get_config()
{
bool done = false;
wcstring result;
env_var_t xdg_dir = env_get_string(L"XDG_CONFIG_HOME", ENV_GLOBAL | ENV_EXPORT);
if (! xdg_dir.missing_or_empty())
{
result = xdg_dir;
append_path_component(result, L"/fish");
if (!create_directory(result))
{
done = true;
}
}
else
{
env_var_t home = env_get_string(L"HOME", ENV_GLOBAL | ENV_EXPORT);
if (! home.missing_or_empty())
{
result = home;
append_path_component(result, L"/.config/fish");
if (!create_directory(result))
{
done = 1;
}
}
}
if (! done)
{
/* Bad juju */
debug(0, _(L"Unable to create a configuration directory for fish. Your personal settings will not be saved. Please set the $XDG_CONFIG_HOME variable to a directory where the current user has write access."));
result.clear();
}
return result;
}
bool env_universal_t::load()
{
scoped_lock locker(lock);
callback_data_list_t callbacks;
const wcstring vars_path = explicit_vars_path.empty() ? default_vars_path() : explicit_vars_path;
bool success = load_from_path(vars_path, &callbacks);
if (! success && ! tried_renaming && errno == ENOENT)
{
/* We failed to load, because the file was not found. Older fish used the hostname only. Try *moving* the filename based on the hostname into place; if that succeeds try again. Silently "upgraded." */
tried_renaming = true;
wcstring hostname_id;
if (get_hostname_identifier(&hostname_id))
{
const wcstring hostname_path = wdirname(vars_path) + L'/' + hostname_id;
if (0 == wrename(hostname_path, vars_path))
{
/* We renamed - try again */
success = this->load();
}
}
}
return success;
}
bool env_universal_t::open_temporary_file(const wcstring &directory, wcstring *out_path, int *out_fd)
{
/* Create and open a temporary file for writing within the given directory */
/* Try to create a temporary file, up to 10 times. We don't use mkstemps because we want to open it CLO_EXEC. This should almost always succeed on the first try. */
assert(! string_suffixes_string(L"/", directory));
bool success = false;
const wcstring tmp_name_template = directory + L"/fishd.tmp.XXXXXX";
wcstring tmp_name;
for (size_t attempt = 0; attempt < 10 && ! success; attempt++)
{
int result_fd = -1;
char *narrow_str = wcs2str(tmp_name_template.c_str());
#if HAVE_MKOSTEMP
result_fd = mkostemp(narrow_str, O_CLOEXEC);
if (result_fd >= 0)
{
tmp_name = str2wcstring(narrow_str);
}
#else
if (mktemp(narrow_str))
{
/* It was successfully templated; try opening it atomically */
tmp_name = str2wcstring(narrow_str);
result_fd = wopen_cloexec(tmp_name, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, 0644);
}
#endif
if (result_fd >= 0)
{
/* Success */
*out_fd = result_fd;
*out_path = str2wcstring(narrow_str);
success = true;
}
free(narrow_str);
}
if (! success)
{
int err = errno;
report_error(err, L"Unable to open file '%ls'", tmp_name.c_str());
}
return success;
}
bool env_universal_t::open_and_acquire_lock(const wcstring &path, int *out_fd)
{
/* Attempt to open the file for reading at the given path, atomically acquiring a lock. On BSD, we can use O_EXLOCK. On Linux, we open the file, take a lock, and then compare fstat() to stat(); if they match, it means that the file was not replaced before we acquired the lock.
We pass O_RDONLY with O_CREAT; this creates a potentially empty file. We do this so that we have something to lock on.
*/
int result_fd = -1;
bool needs_lock = true;
int flags = O_RDONLY | O_CREAT;
#ifdef O_EXLOCK
flags |= O_EXLOCK;
needs_lock = false;
#endif
for (;;)
{
int fd = wopen_cloexec(path, flags, 0644);
if (fd < 0)
{
int err = errno;
if (err == EINTR)
{
/* Signal; try again */
continue;
}
#ifdef O_EXLOCK
else if (err == EOPNOTSUPP)
{
/* Filesystem probably does not support locking. Clear the flag and try again. Note that we try taking the lock via flock anyways. */
flags &= ~O_EXLOCK;
needs_lock = true;
continue;
}
#endif
else
{
report_error(err, L"Unable to open universal variable file '%ls'", path.c_str());
break;
}
}
/* If we get here, we must have a valid fd */
assert(fd >= 0);
/* Try taking the lock, if necessary. If we failed, we may be on lockless NFS, etc.; in that case we pretend we succeeded. See the comment in save_to_path for the rationale. */
if (needs_lock)
{
while (flock(fd, LOCK_EX) < 0)
{
/* error */
if (errno != EINTR)
{
int err = errno;
report_error(err, L"Unable to lock universal variable file '%ls'", path.c_str());
break;
}
}
}
/* Hopefully we got the lock. However, it's possible the file changed out from under us while we were waiting for the lock. Make sure that didn't happen. */
if (file_id_for_fd(fd) != file_id_for_path(path))
{
/* Oops, it changed! Try again */
close(fd);
continue;
}
/* Finally, we have an fd that's valid and hopefully locked. We're done */
assert(fd >= 0);
result_fd = fd;
break;
}
*out_fd = result_fd;
return result_fd >= 0;
}
/* Returns true if modified variables were written, false if not. (There may still be variable changes due to other processes on a false return). */
bool env_universal_t::sync(callback_data_list_t *callbacks)
{
UNIVERSAL_LOG("sync");
scoped_lock locker(lock);
/* Our saving strategy:
1. Open the file, producing an fd.
2. Lock the file (may be combined with step 1 on systems with O_EXLOCK)
3. After taking the lock, check if the file at the given path is different from what we opened. If so, start over.
4. Read from the file. This can be elided if its dev/inode is unchanged since the last read
5. Open an adjacent temporary file
6. Write our changes to an adjacent file
7. Move the adjacent file into place via rename. This is assumed to be atomic.
8. Release the lock and close the file
Consider what happens if Process 1 and 2 both do this simultaneously. Can there be data loss? Process 1 opens the file and then attempts to take the lock. Now, either process 1 will see the original file, or process 2's new file. If it sees the new file, we're OK: it's going to read from the new file, and so there's no data loss. If it sees the old file, then process 2 must have locked it (if process 1 locks it, switch their roles). The lock will block until process 2 reaches step 7; at that point process 1 will reach step 2, notice that the file has changed, and then start over.
It's possible that the underlying filesystem does not support locks (lockless NFS). In this case, we risk data loss if two shells try to write their universal variables simultaneously. In practice this is unlikely, since uvars are usually written interactively.
Prior versions of fish used a hard link scheme to support file locking on lockless NFS. The risk here is that if the process crashes or is killed while holding the lock, future instances of fish will not be able to obtain it. This seems to be a greater risk than that of data loss on lockless NFS. Users who put their home directory on lockless NFS are playing with fire anyways.
*/
const wcstring &vars_path = explicit_vars_path.empty() ? default_vars_path() : explicit_vars_path;
/* If we have no changes, just load */
if (modified.empty())
{
this->load_from_path(vars_path, callbacks);
return false;
}
const wcstring directory = wdirname(vars_path);
bool success = true;
int vars_fd = -1;
int private_fd = -1;
wcstring private_file_path;
UNIVERSAL_LOG("Performing full sync");
/* Open the file */
if (success)
{
success = this->open_and_acquire_lock(vars_path, &vars_fd);
}
/* Read from it */
if (success)
{
assert(vars_fd >= 0);
this->load_from_fd(vars_fd, callbacks);
}
/* Open adjacent temporary file */
if (success)
{
success = this->open_temporary_file(directory, &private_file_path, &private_fd);
}
/* Write to it */
if (success)
{
assert(private_fd >= 0);
success = this->write_to_fd(private_fd, private_file_path);
}
if (success)
{
/* Apply new file */
success = this->move_new_vars_file_into_place(private_file_path, vars_path);
}
if (success)
{
/* Since we moved the new file into place, clear the path so we don't try to unlink it */
private_file_path.clear();
}
/* Clean up */
if (vars_fd >= 0)
{
close(vars_fd);
}
if (private_fd >= 0)
{
close(private_fd);
}
if (! private_file_path.empty())
{
wunlink(private_file_path);
}
if (success)
{
/* All of our modified variables have now been written out. */
modified.clear();
}
return success;
}
var_table_t env_universal_t::read_message_internal(int fd)
{
var_table_t result;
// Temp value used to avoid repeated allocations
wcstring storage;
// The line we construct (and then parse)
std::string line;
wcstring wide_line;
for (;;)
{
// Read into a buffer. Note this is NOT null-terminated!
char buffer[1024];
ssize_t amt = read_loop(fd, buffer, sizeof buffer);
if (amt <= 0)
{
break;
}
const size_t bufflen = (size_t)amt;
// Walk over it by lines. The contents of an unterminated line will be left in 'line' for the next iteration.
size_t line_start = 0;
while (line_start < amt)
{
// Run until we hit a newline
size_t cursor = line_start;
while (cursor < bufflen && buffer[cursor] != '\n')
{
cursor++;
}
// Copy over what we read
line.append(buffer + line_start, cursor - line_start);
// Process it if it's a newline (which is true if we are before the end of the buffer)
if (cursor < bufflen && ! line.empty())
{
if (utf8_to_wchar_string(line, &wide_line))
{
env_universal_t::parse_message_internal(wide_line, &result, &storage);
}
line.clear();
}
// Skip over the newline (or skip past the end)
line_start = cursor + 1;
}
}
// We make no effort to handle an unterminated last line
return result;
}
/**
Parse message msg
*/
void env_universal_t::parse_message_internal(const wcstring &msgstr, var_table_t *vars, wcstring *storage)
{
const wchar_t *msg = msgstr.c_str();
// debug( 3, L"parse_message( %ls );", msg );
if (msg[0] == L'#')
return;
bool is_set_export = match(msg, SET_EXPORT_STR);
bool is_set = ! is_set_export && match(msg, SET_STR);
if (is_set || is_set_export)
{
const wchar_t *name, *tmp;
const bool exportv = is_set_export;
name = msg+(exportv?wcslen(SET_EXPORT_STR):wcslen(SET_STR));
while (name[0] == L'\t' || name[0] == L' ')
name++;
tmp = wcschr(name, L':');
if (tmp)
{
/* Use 'storage' to hold our key to avoid allocations */
storage->assign(name, tmp - name);
const wcstring &key = *storage;
wcstring val;
if (unescape_string(tmp + 1, &val, 0))
{
var_entry_t &entry = (*vars)[key];
entry.exportv = exportv;
entry.val.swap(val); //acquire the value
}
}
else
{
debug(1, PARSE_ERR, msg);
}
}
else
{
debug(1, PARSE_ERR, msg);
}
}
/**
Maximum length of hostname. Longer hostnames are truncated
*/
#define HOSTNAME_LEN 32
/* Length of a MAC address */
#define MAC_ADDRESS_MAX_LEN 6
/* Thanks to Jan Brittenson
http://lists.apple.com/archives/xcode-users/2009/May/msg00062.html
*/
#ifdef SIOCGIFHWADDR
/* Linux */
#include <net/if.h>
static bool get_mac_address(unsigned char macaddr[MAC_ADDRESS_MAX_LEN], const char *interface = "eth0")
{
bool result = false;
const int dummy = socket(AF_INET, SOCK_STREAM, 0);
if (dummy >= 0)
{
struct ifreq r;
strncpy((char *)r.ifr_name, interface, sizeof r.ifr_name - 1);
r.ifr_name[sizeof r.ifr_name - 1] = 0;
if (ioctl(dummy, SIOCGIFHWADDR, &r) >= 0)
{