Scapy AsyncSniffer fails if stop() is called right after start() - asynchronous

Look at the following example
a = AsyncSniffer()
a.start()
a.stop()
a.stop() will throw an exception. Is there a way to fix this without adding a time.sleep() between the start() and stop()?
this ofcourse is a contrived example but the code in our project has the same problem if I create a test stub in between the start() and the stop()
Update:
tracebak from pycharm run:
FAILED [100%]
test_async_sniffer.py:3 (test_async_sniffer)
self = <scapy.sendrecv.AsyncSniffer object at 0x7f1d57a7f1f0>, join = True
def stop(self, join=True):
"""Stops AsyncSniffer if not in async mode"""
if self.running:
try:
> self.stop_cb()
E AttributeError: 'AsyncSniffer' object has no attribute 'stop_cb'
venv/lib/python3.8/site-packages/scapy/sendrecv.py:1017: AttributeError
During handling of the above exception, another exception occurred:
def test_async_sniffer():
a = AsyncSniffer()
a.start()
> a.stop()
test_async_sniffer.py:7:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <scapy.sendrecv.AsyncSniffer object at 0x7f1d57a7f1f0>, join = True
def stop(self, join=True):
"""Stops AsyncSniffer if not in async mode"""
if self.running:
try:
self.stop_cb()
except AttributeError:
> raise Scapy_Exception(
"Unsupported (offline or unsupported socket)"
)
E scapy.error.Scapy_Exception: Unsupported (offline or unsupported socket)
venv/lib/python3.8/site-packages/scapy/sendrecv.py:1019: Scapy_Exception

A possible answer although not pretty:
a = AsyncSniffer()
a.start()
if not hasattr(a, 'stop_cb'):
time.sleep(0.06)
a.stop()
seems the start() creates the attribute stop_cb, and if stop() is called right after start() the stop_cb has not been created yet, so I add an hasattr with a sleep (testing shows 0.06 secs is sufficient time but I guess it's very arbitrary)

Related

How to convert PDF pages to PNG using Ghostscript Wrapper VB.NET?

I'm trying convert from digitally signed PDF to PNG using this solution: Simple VB.Net Wrapper for Ghostscript Dll. It doesn't work for me too. I'm using Ghostscript 9.18 32bits.
First, the source code goes to InOutErrCallBack method in this part:
gsapi_init_with_args(InstanceHndl, NumArgs + 1, Args)
When this occurr, the execution freeze. After this occurs, the next calls to RunGS method returns false in this part:
If gsapi_new_instance(InstanceHndl, IntPtr.Zero) <> 0 Then
Return False
Exit Function
End If
The return value of gsapi_new_instance is -100:
Ghostscript API - Return codes
The gswin32.dll is in C:\Windows\System32 and BIN project folder.
My parameter sequence:
Dim outputImgPath As String
outputImgPath = "C:\Download\DocumentosV2\Protocolo\Pronunciamento\" + Guid.NewGuid.ToString("N") + ".png"
Dim args() As String = { _
"-dNOPAUSE", _
"-dBATCH", _
"-dSAFER", _
"-dQUIET", _
"-sDEVICE=png16m", _
String.Format("-r{0}", resolucao), _
"-dTextAlphaBits=2", _
"-dGraphicsAlphaBits=2", _
String.Format("-dFirstPage={0}", pageNumber), _
String.Format("-dLastPage={0}", pageNumber), _
String.Format("-sOutputFile={0}", outputImgPath), _
"-f", _
pdfPath _
}
UPDATE
#kens advise me for some arguments. So, I remove it to test.
My Complete code:
Imports PdfSharp
Imports System
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Drawing
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports PdfSharp.Drawing
'''
''' http://www.geekscrapbook.com/2009/11/16/c-method-to-add-an-image-to-a-pdf/
'''
Public Class PDF2Image2PDF
Inherits Simp.Net.Infra.SimpComponent
Private SyncRoot As New Object
'Converte cada página do PDF em imagem
Public Function Pdf2Png(ByVal pdfPath As String, ByVal resolucao As Int32) As Image()
Dim outputImgPath As String
Dim pageCount As Integer
Dim objPdfReader As New iTextSharp.text.pdf.PdfReader(pdfPath)
pageCount = objPdfReader.NumberOfPages()
Dim objImages As New ArrayList
For pageNumber As Int32 = 1 To pageCount
outputImgPath = "C:/Download/DocumentosV2/Protocolo/Pronunciamento/" + Guid.NewGuid.ToString("N") + ".png"
Dim objFileStream As FileStream
Dim objMemoryStream As MemoryStream
'Dim args() As String = { _
' "-dNOPAUSE", _
' "-dBATCH", _
' "-dSAFER", _
' "-dQUIET", _
' "-sDEVICE=png16m", _
' String.Format("-r{0}", resolucao), _
' "-dTextAlphaBits=2", _
' "-dGraphicsAlphaBits=2", _
' String.Format("-dFirstPage={0}", pageNumber), _
' String.Format("-dLastPage={0}", pageNumber), _
' String.Format("-sOutputFile={0}", outputImgPath), _
' "-f", _
' pdfPath _
' }
Dim args() As String = { _
"-dNOPAUSE", _
"-dBATCH", _
"-sDEVICE=png16m", _
String.Format("-dFirstPage={0}", pageNumber), _
String.Format("-dLastPage={0}", pageNumber), _
String.Format("-sOutputFile={0}", outputImgPath), _
Replace(pdfPath, "\", "/") _
}
If GhostscriptDllLib.RunGS(args) Then
If File.Exists(outputImgPath) Then
objFileStream = New FileStream(outputImgPath, FileMode.Open)
Dim length As Int32 = objFileStream.Length
Dim bytes(length) As Byte
objFileStream.Read(bytes, 0, length)
objFileStream.Close()
objMemoryStream = New MemoryStream(bytes, False)
objImages.Add(Image.FromStream(objMemoryStream))
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Next
Return CType(objImages.ToArray(GetType(Image)), Image())
End Function
'Converte cada imagem do vetor em uma página do PDF
Public Function Images2PDF(ByVal imagens() As Image) As PdfDocument
Dim pdf As PdfDocument
Dim gfx As XGraphics
Dim ximg As XImage
pdf = New PdfDocument
For Each img As Image In imagens
pdf.AddPage(New PdfPage)
gfx = XGraphics.FromPdfPage(pdf.Pages.Item(0))
ximg = XImage.FromGdiPlusImage(img)
gfx.DrawImage(ximg, 0, 0)
ximg.Dispose()
gfx.Dispose()
Next
Return pdf
End Function
End Class
The Caller code:
Public Sub DownloadPeticionamento(ByVal sender As System.Object, ByVal e As System.web.UI.ImageClickEventArgs)
Dim imagem As ImageButton = DirectCast(sender, ImageButton)
Dim pdfPath As String = imagem.DescriptionUrl
Dim objPdfPeticionamento As New Simp.Net.Negocio.PDF2Image2PDF
Dim objImages() As Image
Dim objPdfDoc As PdfDocument
objImages = objPdfPeticionamento.Pdf2Png(pdfPath, 600)
objPdfDoc = objPdfPeticionamento.Images2PDF(objImages)
objPdfDoc.Save(Me.Page.Response.OutputStream, True)
End Sub
I test this in command line to:
gswin32c -dNOPAUSE -dBATCH -sDEVICE=png16m -sOutputFile=C:/Download/DocumentosV2/Protocolo/Pronunciamento/fb21872746b64f8fb31b3764b5444e2e.png C:/Upload/DocumentosV2/Protocolo/Pronunciamento/3_0_404702190_2016_10081288_230_0_f1f09b4b38ac49a8a3e5576f6041eea3.pdf
Via command line, the pdf is converted. The command line output:
C:\Documents and Settings\leandro.ferreira>gswin32c -dNOPAUSE -dBATCH -sDEVICE=png16m -dFirstPage=1 -dLastPage=1 -sOutputFile=C:/Download/DocumentosV2/Protocolo/Pronunciamento/fb21872746b64f8fb31b3764b5444e2e.png C:/Upload/DocumentosV2/Protocolo/Pronunciamento/3_0_404702190_2016_10081288_230_0_f1f09b4b38ac49a8a3e5576f6041eea3.pdf
GPL Ghostscript 9.16 (2015-03-30)
Copyright (C) 2015 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
Can't find (or can't open) font file %rom%Resource/Font/Arial-BoldMT.
Can't find (or can't open) font file Arial-BoldMT.
Can't find (or can't open) font file %rom%Resource/Font/Arial-BoldMT.
Can't find (or can't open) font file Arial-BoldMT.
Querying operating system for font files...
Didn't find this font on the system!
Substituting font Helvetica-Bold for Arial-BoldMT.
Loading NimbusSan-Bol font from %rom%Resource/Font/NimbusSan-Bol... 4047240 2487522 8937716 7603550 3 done.
Can't find (or can't open) font file %rom%Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Can't find (or can't open) font file %rom%Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Didn't find this font on the system!
Substituting font Helvetica for ArialMT.
Loading NimbusSan-Reg font from %rom%Resource/Font/NimbusSan-Reg... 4080352 2580805 9014744 7662839 3 done.
C:\Documents and Settings\leandro.ferreira>
-100 is simply 'fatal error' ie something really bad happened. More information is generally printed to stdout or stderr, of course setting -dQUIET will suppress much of this....
Since you are getting -100 returned its almost certainly the case that your arguments to Ghostscript are incorrect in some way.
The absolute first thing you should do when debugging problems is to try and simplify the problem, so remove any switches that you don't unquestionably require.
So the first thing to do is to remove the -dQUIET, capture all the stdout/stderr output and tell us what it says.
Further to that, note the following:
You don't need '-f' because the only purpose of that switch is to terminate -c which you haven't used.
You haven't given the values of 'resolucao', 'pageNumber', or 'pdfPath' or so there's no way to know if those are valid (or sensible). The path you have specified for outputImgPath is quite long, and includes the backslash character. I would advise using the forward slash '/' instead, as backslash is used to begin an escape and can give results you may not expect.
You've also used -dSAFER, do you understand the implications of specifying this ? If not, remove it and try again.
When you have created the string 'args' print it out. At the very least this will give you something you can try from the command line, and may mean that other people have some chance of reproducing your problem.
Finally; please note that Ghostscript is distributed under the Affero General Public Licence, please be sure to read the licence and ensure that you are conforming to the terms contained therein.
To do this work, I modified the Simple VB.Net Wrapper for Ghostscript Dll CallBack:
Private Function InOutErrCallBack(ByVal handle As IntPtr, _
ByVal Strz As IntPtr, ByVal Bytes As Integer) As Integer
Dim objString As String
objString = Marshal.PtrToStringAnsi(Strz, Bytes)
System.Diagnostics.Debug.WriteLine(objString)
Return Bytes
End Function
This wrotes the Ghostscript output into the Output window's Visual Studio 2003. I removed the extra "needless" arguments to Ghostscript, like -dGraphicsAlphaBits. The asp.net user does not access the Path.GetTempDir, so, I need a different "temp" dir.
'Converte cada página do PDF em imagem
Public Function Pdf2Png(ByVal pdfPath As String, ByVal tempDirPath As String, ByVal resolucao As Int32) As Image()
Dim outputImgPath As String
Dim pageCount As Integer
Dim objPdfReader As New iTextSharp.text.pdf.PdfReader(pdfPath)
pageCount = objPdfReader.NumberOfPages()
Dim objImages As New ArrayList
For pageNumber As Int32 = 1 To pageCount
outputImgPath = tempDirPath + Guid.NewGuid.ToString("N") + ".png"
Dim objFileStream As FileStream
Dim objMemoryStream As MemoryStream
'Dim args() As String = { _
' "-dNOPAUSE", _
' "-dBATCH", _
' "-dSAFER", _
' "-dQUIET", _
' "-sDEVICE=png16m", _
' String.Format("-r{0}", resolucao), _
' "-dTextAlphaBits=2", _
' "-dGraphicsAlphaBits=2", _
' String.Format("-dFirstPage={0}", pageNumber), _
' String.Format("-dLastPage={0}", pageNumber), _
' String.Format("-sOutputFile={0}", outputImgPath), _
' "-f", _
' pdfPath _
' }
Dim args() As String = { _
"-dNOPAUSE", _
"-dBATCH", _
"-sDEVICE=png16m", _
String.Format("-dFirstPage={0}", pageNumber), _
String.Format("-dLastPage={0}", pageNumber), _
String.Format("-sOutputFile={0}", outputImgPath), _
Replace(pdfPath, "\", "/") _
}
If GhostscriptDllLib.RunGS(args) Then
If File.Exists(outputImgPath) Then
objFileStream = New FileStream(outputImgPath, FileMode.Open)
Dim length As Int32 = objFileStream.Length
Dim bytes(length) As Byte
objFileStream.Read(bytes, 0, length)
objFileStream.Close()
objMemoryStream = New MemoryStream(bytes, False)
objImages.Add(Image.FromStream(objMemoryStream))
File.Delete(outputImgPath)
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Next
Return CType(objImages.ToArray(GetType(Image)), Image())
End Function

Cannot apply operator && to operands of type String and String()

I'm having cannot apply operator && to operands of type String and String() at the below code. Anyone knows what's the cause for this issue?
If IsValidEmail(EmailAddress) Then
EncodedData += "&data[]=" +
+ HttpContext.Current.Server.UrlEncode( _
(Convert.ToString((Convert.ToString("{""email"":""") _
& EmailAddresses) + """,""name"":""") & Name) + """}")
End If
If EmailAddresses is an array, you have to decide how to combine the potentially multiple values in there.
Maybe, something like:
String.Join(";",EmailAddresses)
So that the addresses are ; separated? Or maybe, since this is inside an If block that checks a different, but probably related variable, you intended this reference to be EmailAddress, not EmailAddresses.
So, either:
EncodedData += "&data[]=" _
& HttpContext.Current.Server.UrlEncode("{""email"":""" _
& String.Join(";",EmailAddresses) & """,""name"":""" _
& Name & """}")
or:
EncodedData += "&data[]=" _
& HttpContext.Current.Server.UrlEncode("{""email"":""" _
& EmailAddress & """,""name"":""" _
& Name & """}")
Where I've also removed the pointless conversions of strings into (better?) strings and the mixing of string concatenation operators.

Creating a webservice that accepts XML as a string

I have been trying to create a webservice that needs to allow the client to send thru 3 parameters being Username, Password and XML_In all 3 of type string. This then sends the variables to a Stored procedure which processes the data and returns an XML string which is then returned to the client.
The Stored procedure works 100% but I'm getting an error with the XML being sent thru as a string. From reading up most gave the suggestion of adding <httpRuntime requestValidationMode="2.0"/> and <pages validateRequest="false"> to my web.config which works but that would then apply to my entire site which I dont want at all.
The other suggestion was to place it in the #Page part but that does not apply to a web service as it has no user defined layout. Please see my code below and help. I'm still quite a newbie to .Net thus the reason I'm doing 90% of it in SQL.
The error That gets returned is :
System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (XML_In="<senddata><settings ...").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.ValidateHttpValueCollection(HttpValueCollection collection, RequestValidationSource requestCollection)
at System.Web.HttpRequest.get_Form()
at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
here's the code:
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Xml
Imports JumpStart.Framework.Database
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://mydomainname.co.za/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class LeadProcessor
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & XML_In.ToString & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
I agree with CodeCaster comment (new projects - WCF or WebApi).
But if you can't change it now, consider use a XMLDocument as parameter, or an XElemento, or directly, do a Base64 transform of the text, in order to avoid that errors.
Code for your service' client:
your_proxy.Lead_Processing(sUserName, sPassWord, Convert.ToBase64String(Encoding.UTF8.GetBytes(sXML))
Then, in your service, do this
<WebMethod()> _
Public Function Lead_Processing(ByVal UserName As String, ByVal PassWord As String, ByVal XML_In As String) As XmlDocument
Dim oData As Byte() = Convert.FromBase64String(XML_In)
Dim sDecodedXML As String = System.Text.Encoding.UTF8.GetString(oData)
Dim poDSL As New DSL
Dim Result As String
Dim XML_Out = New XmlDocument()
Result = poDSL.ExecuteProcedure_ExecuteScalar("DECLARE #Result XML " & _
"EXEC [dbo].[APP_InsertLeadFromXML] " & _
"#Username = N'" & UserName & "', " & _
"#Password = N'" & PassWord & "', " & _
"#ParmListXML = '" & sDecodedXML & "', " & _
"#XMLResult = #Result OUTPUT " & _
"SELECT #Result")
XML_Out.LoadXml(Result)
Return XML_Out
End Function
Hope it helps
Edit:
Your service with base64.
We're telling that Asmx it's almost a legacy tech. New projects may use WCF tech (I can't teach you WCF in a few lines).
You can put that code into your asmx service. You can use that code in the way I edited my answer.

VB.Net and XDocument - Group By

I have the following code which I need to amend to group by offer but I'm not sure how to add in the group by part in this query.
Any ideas?
propertyInfo = myXmlFile.Descendants("offer").Descendants("site") _
.Where(Function(f) _
f.Attributes("code").First.Value = Location.Text) _
.Select(Function(f) New With { _
.LOCATION = f.Attributes("code").First.Value, _
.TITLE = f.Parent.Attributes("title").First.Value, _
.OFFER = f.Parent.Attributes("offerid").First.Value, _
.POPUPDESC = f.Parent.Descendants("short_desc").Value
Example XML
<offers>
<offer title="Offer title" offerid="AS32">
<short_desc><![CDATA[
<div>Your HTML's body <a href='dfgdfgdfgdfg.html'>Offer title</a>
</div>
]]></short_desc>
<site code="CO">
<year_week_start>201344</year_week_start>
<year_week_end>201414</year_week_end>
</site>
<site code="FH">
<year_week_start>201446</year_week_start>
<year_week_end>201450</year_week_end>
</site>
</offer>
</offers>
I think you need to be a little more specific in what you want after you group. It's pretty easy to group, but then you get an enumerable of groups:
propertyInfo = myXmlFile.Descendants("offer").Descendants("site") _
.Where(Function(f) _
f.Attributes("code").First.Value = Location.Text) _
.Select(Function(f) New With { _
.LOCATION = f.Attributes("code").First.Value, _
.TITLE = f.Parent.Attributes("title").First.Value, _
.OFFER = f.Parent.Attributes("offerid").First.Value, _
.POPUPDESC = f.Parent.Descendants("short_desc").Value) _
.GroupBy(Function(f) f.OFFER)

LINQ to Entities does not recognize the method - simple delete statement

I have a GridView and on a row being deleted I trigger the GridView1_RowDeleting sub, but I receive an error "LINQ to Entities does not recognize the method 'System.Web.UI.WebControls.TableCell get_Item(Int32)' method, and this method cannot be translated into a store expression." Code is:
Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
' The deletion of the individual row is automatically handled by the GridView.
Dim dbDelete As New pbu_housingEntities
' Remove individual from the bed.
Dim remove_bed = From p In dbDelete.Beds _
Where p.occupant = GridView1.Rows(e.RowIndex).Cells(3).Text _
Where p.room = GridView1.Rows(e.RowIndex).Cells(6).Text _
Where p.building = GridView1.Rows(e.RowIndex).Cells(5).Text _
Order By p.id Descending _
Select p
remove_bed.First.occupant = ""
dbDelete.SaveChanges()
' Increase number of open spaces in room.
Dim update_occupancy = From p In dbDelete.Rooms _
Where p.room1 = GridView1.Rows(e.RowIndex).Cells(6).Text
Where p.building = GridView1.Rows(e.RowIndex).Cells(5).Text _
Select p
update_occupancy.First.current_occupancy = update_occupancy.First.current_occupancy - 1
dbDelete.SaveChanges()
End Sub
The specific line erroring out is:
remove_bed.First.occupant = ""
That's because the Linq query is translated to SQL, and there is no way to translate GridView1.Rows(e.RowIndex).Cells(3).Text to SQL. You need to extract the values from the GridView, then use them in the query
Dim occupant As String = GridView1.Rows(e.RowIndex).Cells(3).Text
Dim room As String = GridView1.Rows(e.RowIndex).Cells(6).Text
Dim building As String = GridView1.Rows(e.RowIndex).Cells(5).Text
Dim remove_bed = From p In dbDelete.Beds _
Where p.occupant = occupant _
Where p.room = room _
Where p.building = building _
Order By p.id Descending _
Select p
You have to put those values in variables before executing the query, otherwise the Entity Provider will try to pull the whole object into the query and access it's properties when it is trying to translate it into a SQL statement - which fails since there is no SQL equivalent.

Resources