diff --git a/pcap.js b/pcap.js index cd31439..687ac6d 100644 --- a/pcap.js +++ b/pcap.js @@ -101,11 +101,14 @@ PcapSession.prototype.on_packet_ready = function () { PcapSession.prototype.close = function () { this.opened = false; - this.session.close(); + + this.removeAllListeners(); + if (this.is_live) { this.readWatcher.stop(); } - // TODO - remove listeners so program will exit I guess? + + this.session.close(); }; PcapSession.prototype.stats = function () { diff --git a/pcap_session.cc b/pcap_session.cc index 46540fc..456e5bd 100644 --- a/pcap_session.cc +++ b/pcap_session.cc @@ -119,6 +119,10 @@ void PcapSession::Dispatch(const Nan::FunctionCallbackInfo& info) int packet_count; do { packet_count = pcap_dispatch(session->pcap_handle, 1, PacketReady, (u_char *)session); + + if (packet_count == -2) { + FinalizeClose(session); + } } while (packet_count > 0); info.GetReturnValue().Set(Nan::New(packet_count)); @@ -313,9 +317,16 @@ void PcapSession::Close(const Nan::FunctionCallbackInfo& info) session->pcap_dump_handle = NULL; } + if (session->pcap_handle != NULL) { + pcap_breakloop(session->pcap_handle); + } +} + +void PcapSession::FinalizeClose(PcapSession * session) { pcap_close(session->pcap_handle); + session->pcap_handle = NULL; + session->packet_ready_cb.Reset(); - return; } void PcapSession::Fileno(const Nan::FunctionCallbackInfo& info) @@ -324,6 +335,11 @@ void PcapSession::Fileno(const Nan::FunctionCallbackInfo& info) PcapSession* session = Nan::ObjectWrap::Unwrap(info.Holder()); + if (session->pcap_handle == NULL) { + Nan::ThrowError("Error: pcap session already closed"); + return; + } + int fd = pcap_get_selectable_fd(session->pcap_handle); info.GetReturnValue().Set(Nan::New(fd)); @@ -337,6 +353,11 @@ void PcapSession::Stats(const Nan::FunctionCallbackInfo& info) PcapSession* session = Nan::ObjectWrap::Unwrap(info.Holder()); + if (session->pcap_handle == NULL) { + Nan::ThrowError("Error: pcap session already closed"); + return; + } + if (pcap_stats(session->pcap_handle, &ps) == -1) { Nan::ThrowError("Error in pcap_stats"); return; @@ -368,6 +389,12 @@ void PcapSession::Inject(const Nan::FunctionCallbackInfo& info) } PcapSession* session = Nan::ObjectWrap::Unwrap(info.Holder()); + + if (session->pcap_handle == NULL) { + Nan::ThrowError("Error: pcap session already closed"); + return; + } + char * bufferData = NULL; size_t bufferLength = 0; Local buffer_obj = info[0]->ToObject(); diff --git a/pcap_session.h b/pcap_session.h index 57bbfc3..7630881 100644 --- a/pcap_session.h +++ b/pcap_session.h @@ -22,6 +22,7 @@ class PcapSession : public Nan::ObjectWrap { static void Stats(const Nan::FunctionCallbackInfo& info); static void Inject(const Nan::FunctionCallbackInfo& info); static void PacketReady(u_char *callback_p, const struct pcap_pkthdr* pkthdr, const u_char* packet); + static void FinalizeClose(PcapSession *session); Nan::Persistent packet_ready_cb; static Nan::Persistent constructor;