1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 #include "async_wrap-inl.h"
23 #include "env-inl.h"
24 #include "node.h"
25 #include "handle_wrap.h"
26 #include "string_bytes.h"
27
28
29 namespace node {
30
31 using v8::Context;
32 using v8::DontDelete;
33 using v8::DontEnum;
34 using v8::FunctionCallbackInfo;
35 using v8::FunctionTemplate;
36 using v8::HandleScope;
37 using v8::Integer;
38 using v8::Local;
39 using v8::MaybeLocal;
40 using v8::Object;
41 using v8::PropertyAttribute;
42 using v8::ReadOnly;
43 using v8::Signature;
44 using v8::String;
45 using v8::Value;
46
47 namespace {
48
49 class FSEventWrap: public HandleWrap {
50 public:
51 static void Initialize(Local<Object> target,
52 Local<Value> unused,
53 Local<Context> context,
54 void* priv);
55 static void New(const FunctionCallbackInfo<Value>& args);
56 static void Start(const FunctionCallbackInfo<Value>& args);
57 static void GetInitialized(const FunctionCallbackInfo<Value>& args);
58
59 SET_NO_MEMORY_INFO()
60 SET_MEMORY_INFO_NAME(FSEventWrap)
61 SET_SELF_SIZE(FSEventWrap)
62
63 private:
64 static const encoding kDefaultEncoding = UTF8;
65
66 FSEventWrap(Environment* env, Local<Object> object);
67 ~FSEventWrap() override = default;
68
69 static void OnEvent(uv_fs_event_t* handle, const char* filename, int events,
70 int status);
71
72 uv_fs_event_t handle_;
73 enum encoding encoding_ = kDefaultEncoding;
74 };
75
76
FSEventWrap(Environment * env,Local<Object> object)77 FSEventWrap::FSEventWrap(Environment* env, Local<Object> object)
78 : HandleWrap(env,
79 object,
80 reinterpret_cast<uv_handle_t*>(&handle_),
81 AsyncWrap::PROVIDER_FSEVENTWRAP) {
82 MarkAsUninitialized();
83 }
84
85
GetInitialized(const FunctionCallbackInfo<Value> & args)86 void FSEventWrap::GetInitialized(const FunctionCallbackInfo<Value>& args) {
87 FSEventWrap* wrap = Unwrap<FSEventWrap>(args.This());
88 CHECK_NOT_NULL(wrap);
89 args.GetReturnValue().Set(!wrap->IsHandleClosing());
90 }
91
Initialize(Local<Object> target,Local<Value> unused,Local<Context> context,void * priv)92 void FSEventWrap::Initialize(Local<Object> target,
93 Local<Value> unused,
94 Local<Context> context,
95 void* priv) {
96 Environment* env = Environment::GetCurrent(context);
97
98 auto fsevent_string = FIXED_ONE_BYTE_STRING(env->isolate(), "FSEvent");
99 Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
100 t->InstanceTemplate()->SetInternalFieldCount(
101 FSEventWrap::kInternalFieldCount);
102 t->SetClassName(fsevent_string);
103
104 t->Inherit(HandleWrap::GetConstructorTemplate(env));
105 env->SetProtoMethod(t, "start", Start);
106
107 Local<FunctionTemplate> get_initialized_templ =
108 FunctionTemplate::New(env->isolate(),
109 GetInitialized,
110 env->as_callback_data(),
111 Signature::New(env->isolate(), t));
112
113 t->PrototypeTemplate()->SetAccessorProperty(
114 FIXED_ONE_BYTE_STRING(env->isolate(), "initialized"),
115 get_initialized_templ,
116 Local<FunctionTemplate>(),
117 static_cast<PropertyAttribute>(ReadOnly | DontDelete | DontEnum));
118
119 target->Set(env->context(),
120 fsevent_string,
121 t->GetFunction(context).ToLocalChecked()).Check();
122 }
123
124
New(const FunctionCallbackInfo<Value> & args)125 void FSEventWrap::New(const FunctionCallbackInfo<Value>& args) {
126 CHECK(args.IsConstructCall());
127 Environment* env = Environment::GetCurrent(args);
128 new FSEventWrap(env, args.This());
129 }
130
131 // wrap.start(filename, persistent, recursive, encoding)
Start(const FunctionCallbackInfo<Value> & args)132 void FSEventWrap::Start(const FunctionCallbackInfo<Value>& args) {
133 Environment* env = Environment::GetCurrent(args);
134
135 FSEventWrap* wrap = Unwrap<FSEventWrap>(args.This());
136 CHECK_NOT_NULL(wrap);
137 CHECK(wrap->IsHandleClosing()); // Check that Start() has not been called.
138
139 const int argc = args.Length();
140 CHECK_GE(argc, 4);
141
142 BufferValue path(env->isolate(), args[0]);
143 CHECK_NOT_NULL(*path);
144
145 unsigned int flags = 0;
146 if (args[2]->IsTrue())
147 flags |= UV_FS_EVENT_RECURSIVE;
148
149 wrap->encoding_ = ParseEncoding(env->isolate(), args[3], kDefaultEncoding);
150
151 int err = uv_fs_event_init(wrap->env()->event_loop(), &wrap->handle_);
152 if (err != 0) {
153 return args.GetReturnValue().Set(err);
154 }
155
156 err = uv_fs_event_start(&wrap->handle_, OnEvent, *path, flags);
157 wrap->MarkAsInitialized();
158
159 if (err != 0) {
160 FSEventWrap::Close(args);
161 return args.GetReturnValue().Set(err);
162 }
163
164 // Check for persistent argument
165 if (!args[1]->IsTrue()) {
166 uv_unref(reinterpret_cast<uv_handle_t*>(&wrap->handle_));
167 }
168
169 args.GetReturnValue().Set(err);
170 }
171
172
OnEvent(uv_fs_event_t * handle,const char * filename,int events,int status)173 void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename,
174 int events, int status) {
175 FSEventWrap* wrap = static_cast<FSEventWrap*>(handle->data);
176 Environment* env = wrap->env();
177
178 HandleScope handle_scope(env->isolate());
179 Context::Scope context_scope(env->context());
180
181 CHECK_EQ(wrap->persistent().IsEmpty(), false);
182
183 // We're in a bind here. libuv can set both UV_RENAME and UV_CHANGE but
184 // the Node API only lets us pass a single event to JS land.
185 //
186 // The obvious solution is to run the callback twice, once for each event.
187 // However, since the second event is not allowed to fire if the handle is
188 // closed after the first event, and since there is no good way to detect
189 // closed handles, that option is out.
190 //
191 // For now, ignore the UV_CHANGE event if UV_RENAME is also set. Make the
192 // assumption that a rename implicitly means an attribute change. Not too
193 // unreasonable, right? Still, we should revisit this before v1.0.
194 Local<String> event_string;
195 if (status) {
196 event_string = String::Empty(env->isolate());
197 } else if (events & UV_RENAME) {
198 event_string = env->rename_string();
199 } else if (events & UV_CHANGE) {
200 event_string = env->change_string();
201 } else {
202 CHECK(0 && "bad fs events flag");
203 }
204
205 Local<Value> argv[] = {
206 Integer::New(env->isolate(), status),
207 event_string,
208 Null(env->isolate())
209 };
210
211 if (filename != nullptr) {
212 Local<Value> error;
213 MaybeLocal<Value> fn = StringBytes::Encode(env->isolate(),
214 filename,
215 wrap->encoding_,
216 &error);
217 if (fn.IsEmpty()) {
218 argv[0] = Integer::New(env->isolate(), UV_EINVAL);
219 argv[2] = StringBytes::Encode(env->isolate(),
220 filename,
221 strlen(filename),
222 BUFFER,
223 &error).ToLocalChecked();
224 } else {
225 argv[2] = fn.ToLocalChecked();
226 }
227 }
228
229 wrap->MakeCallback(env->onchange_string(), arraysize(argv), argv);
230 }
231
232 } // anonymous namespace
233 } // namespace node
234
235 NODE_MODULE_CONTEXT_AWARE_INTERNAL(fs_event_wrap, node::FSEventWrap::Initialize)
236