File: http_client.pl

package info (click to toggle)
swi-prolog 9.0.4%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 82,408 kB
  • sloc: ansic: 387,503; perl: 359,326; cpp: 6,613; lisp: 6,247; java: 5,540; sh: 3,147; javascript: 2,668; python: 1,900; ruby: 1,594; yacc: 845; makefile: 428; xml: 317; sed: 12; sql: 6
file content (349 lines) | stat: -rw-r--r-- 11,739 bytes parent folder | download | duplicates (4)
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
/*  Part of XPCE --- The SWI-Prolog GUI toolkit

    Author:        Jan Wielemaker and Anjo Anjewierden
    E-mail:        jan@swi.psy.uva.nl
    WWW:           http://www.swi.psy.uva.nl/projects/xpce/
    Copyright (c)  2000-2011, University of Amsterdam
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

:- module(pce_http_client, []).
:- use_module(library(pce)).
:- use_module(library(url)).
:- use_module(library(option)).

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This module defines the clas http_client, a subclass of class socket for
fetching data from HTTP servers (aka `web-servers').

It can deal with two HTTP operations

        # GET
        Get data from an URL

        # HEAD
        Get only the header from an URL.

The GET operation is implemented by ->fetch_data:

http_client ->fetch_data: Into:object, Confirm:[code]*, Location:[string]
        Fetches data from the server.  Data is stored into `Into' in
        chunks using `->append: string' to this object.

        If confirm is not @nil, ->fetch_data returns after connecting
        and sending the request to the server.  On completion, the
        Confirm message is executed with

                @arg1   The http_client object
                @arg2   The `Into' object

        If `Confirm' is @nil, ->fetch_data blocks until all data has
        been received.

        In addition to returning the data, the header of the HTTP reply
        is attached to the data in a sheet using the attribute `http_header'.
        Field-names are in lowercase.  The date and last-modified fields
        appear as XPCE date objects and the content-length as an XPCE
        integer.

http_client <-data --> String
        Simple interface to get data.  Returns a string with http_header
        attribute sheet (see above).  Blocks until all data has been received.

http_client <-header --> Sheet
        Yield a sheet containing the header only the header data for the
        URL.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

:- pce_begin_class(http_client, socket,
                   "Client socket for HTTP Protocol").

:- pce_global(@nl_regex, new(regex('\n'))).
:- pce_global(@http_reply_regex,
              new(regex('HTTP/([0-9]\\.[0-9])\\s*(\\d+)\\s*(\\w*)'))).
:- pce_global(@http_field_regex,
              new(regex('([a-zA-Z0-9-]+):\\s*(.*)$'))).
:- pce_global(@http_empty_line_regex,
              new(regex('\\s*\r?$'))).

:- initialization
   new(_, error(http_bad_header,
            '%O: Bad header line: %s',
            warning)),
   new(_, error(url_bad_protocol,
            '%O: Can only handle %s URLs',
            error)),
   new(_, error(url_bad_syntax,
            '%O: Not a legal URL: %s')).

variable(host,         name,           get,  "Host-name of URL").
variable(location,     string,         get,  "Location on server").
variable(message,      code*,          both, "Message send on completion").
variable(data_object,  object*,        get,  "Object holding data").
variable(received,     int*,           get,  "Data received").
variable(remaining,    int*,           get,  "Remaining data").
variable(request,      {header,data}*, get,  "Last request").
variable(req_status,   name*,          get,  "Progress").
variable(http_version, name,           both, "Used version (1.0/1.1)").
variable(user_agent,   name,           both, "Provided User-Agent").
variable(verbose,      {silent,connect,transfer} := connect,
                                       both, "Verbosity").

initialise(S, URL:prolog) :->
    "Create from URL or parsed URL"::
    (   atomic(URL)
    ->  (   parse_url(URL, Parts)
        ->  true
        ;   send(S, error, url_bad_syntax, URL),
            fail
        )
    ;   Parts = URL
    ),
    (   memberchk(protocol(http), Parts)
    ->  true
    ;   send(S, error, url_bad_protocol, 'HTTP'),
        fail
    ),
    option(host(Host), Parts),
    option(port(Port), Parts, 80),
    http_location(Parts, Location),
    send(S, slot, host, Host),
    send(S, slot, location, Location),
    send(S, slot, http_version, '1.0'),
    send(S, slot, user_agent, 'XPCE/SWI-Prolog'),
    send_super(S, initialise, tuple(Host, Port)).

:- pce_group(feedback).

req_status(S, Status:{connecting,connected,header,data,complete}) :->
    "Indicate status changes"::
    send(S, slot, req_status, Status),
    (   get(S, verbose, silent)
    ->  true
    ;   message(Status, S, Message),
        ignore(send(S, Message))
    ).

message(connecting, S, report(progress, 'Connecting %s', Host)) :-
    get(S, host, Host).
message(connected, _, report(progress, 'Connected')).
message(header,    _, report(progress, 'Receiving header')).
message(data,      _, report(progress, 'Receiving data')).
message(complete,  _, report(done)).

progress(S, Progress:int, What:{percent,bytes}) :->
    "Indicate progress"::
    (   get(S, verbose, transfer),
        send(S, report, progress, 'Received %d %s', Progress, What)
    ->  true
    ;   true
    ).

:- pce_group(connect).

connect(S) :->
    "Connect to <-host"::
    (   get(S, status, connected)
    ->  true
    ;   send(S, req_status, connecting),
        send_super(S, connect),
        send(S, req_status, connected)
    ).

:- pce_group(fetch).

fetch_data(S,
           Object:into=object,
           Confirm:confirm=[code]*,
           Location:location=[string]) :->
    "Fetch data from location into Object"::
    send(S, slot, data_object, Object),
    (   Confirm == @default
    ->  true
    ;   send(S, slot, message, Confirm)
    ),
    (   Location == @default
    ->  true
    ;   send(S, slot, location, Location)
    ),
    send(S, slot, request, data),
    send(S, send_header, 'GET'),
    (   get(S, message, Msg),
        Msg \== @nil
    ->  true
    ;   send(S, wait)
    ).

header(S, Location:[string], Header:sheet) :<-
    "Fetch header data from location as a sheet"::
    new(Object, object),
    send(S, slot, data_object, Object),
    (   Location == @default
    ->  true
    ;   send(S, slot, location, Location)
    ),
    send(S, slot, request, header),
    send(S, send_header, 'HEAD'),
    send(S, wait),
    get(Object, http_header, Header),
    send(Header, lock_object, @on),
    send(Object, delete_attribute, http_header),
    get(Header, unlock, _).

data(S, Data:string) :<-
    "Fetch data from location as string"::
    new(TB, text_buffer),
    send(TB, undo_buffer_size, 0),
    send(S, fetch_data, TB),
    get(TB, contents, Data),
    get(TB, http_header, Header),
    send(Data, attribute, http_header, Header),
    free(TB).

:- pce_group(internal).

send_header(S, Action:name) :->
    "Send request header to HTTP server"::
    get(S, host, Host),
    send(S, slot, received, 0),
    send(S, prepare_header),
    send(S, slot, req_status, @nil),
    send(S, connect),
    get(S, http_version, Version),
    get(S, user_agent, Agent),
    get(S, location, Location),
    send(S, format, '%s %s HTTP/%s\r\n', Action, Location, Version),
    send(S, format, 'Host: %s\r\n', Host),
    send(S, format, 'User-Agent: %s\r\n', Agent),
    send(S, format, '\r\n').

wait(S) :->
    "Wait for completion"::
    repeat,
    (   get(S, req_status, complete)
    ->  !
    ;   send(@display, dispatch),
        fail
    ).

prepare_header(S) :->
    "Prepare for receiving header info"::
    send(S, record_separator, @nl_regex),
    send(S, input_message, message(S, header_line, @arg1)),
    send(S?data_object, attribute, http_header, new(sheet)).

header_line(S, Line:string) :->
    "Handle the header lines as they come in"::
    (   send(@http_field_regex, match, Line)
    ->  get(@http_field_regex, register_value, Line, 1, name, FieldName0),
        get(FieldName0, downcase, FieldName),
        get(@http_field_regex, register_value, Line, 2, string, Value),
        send(Value, strip),
        field_type(FieldName, Type),
        get(@pce, convert, Value, Type, FieldValue),
        get(S, data_object, DataObject),
        send(DataObject?http_header, value, FieldName, FieldValue)
    ;   send(@http_reply_regex, match, Line)
    ->  get(S, data_object, DataObject),
        get(@http_reply_regex, register_value, Line, 2, int, ReplyStatus),
        send(DataObject?http_header, value, status, ReplyStatus),
        send(S, req_status, header)
    ;   send(@http_empty_line_regex, match, Line)
    ->  send(S, prepare_data)
    ;   send(S, error, http_bad_header, Line)
    ).

field_type('content-length', int).
field_type('date',           date).
field_type('last-modified',  date).
field_type(_,                name).

prepare_data(S) :->
    "Header has been received, prepare for content"::
    (   get(S, request, header)
    ->  send(S, req_status, complete)
    ;   (   get(S, data_object, Object),
            get(Object?http_header, value, 'content-length', Length)
        ->  send(S, slot, remaining, Length)
        ;   send(S, slot, remaining, @nil)
        ),
        send(S, input_message, message(S, data_record, @arg1)),
        send(S, record_separator, @nil)
    ).

data_record(S, Record:string) :->
    "Receive a data record"::
    get(S, data_object, Data),
    (   get(S, remaining, Rem),
        Rem \== @nil
    ->  get(Record, size, Read),
        NewRem is Rem - Read,
        get(Data?http_header, value, 'content-length', Len),
        Percent is ((Len-NewRem)*100)//Len,
        send(S, progress, Percent, percent),
        (   NewRem >= 0
        ->  send(Data, append, Record),
            send(S, slot, remaining, NewRem),
            (   NewRem == 0
            ->  send(S, complete)
            ;   true
            )
        ;   send(Record, truncate, Rem),
            send(Data, append, Record),
            send(S, complete)
        )
    ;   send(Data, append, Record),
        get(Record, size, Bytes),
        get(S, received, Rec0),
        Rec is Rec0 + Bytes,
        send(S, slot, received, Rec),
        send(S, progress, Rec, bytes)
    ).

end_of_file(S) :->
    "Implicit completion"::
    send(S, close),
    (   get(S, req_status, complete)
    ->  true
    ;   send(S, complete)
    ).

complete(S) :->
    "We received all data"::
    send(S, req_status, complete),
    (   get(S, message, Message),
        Message \== @nil
    ->  get(S, data_object, Data),
        send(Message, forward, S, Data)
    ;   send(S, req_status, complete)
    ).

:- pce_end_class.