File: WebRequest.cpp

package info (click to toggle)
primrose 6%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 5,300 kB
  • ctags: 3,383
  • sloc: cpp: 27,318; php: 765; ansic: 636; objc: 272; sh: 136; makefile: 93; perl: 67
file content (436 lines) | stat: -rw-r--r-- 12,150 bytes parent folder | download | duplicates (5)
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
#include "WebRequest.h"

#include "networkInterface.h"
#include "gameControl.h"

#include "minorGems/util/stringUtils.h"
#include "minorGems/util/StringBufferOutputStream.h"

#include "minorGems/network/SocketClient.h"



WebRequest::WebRequest( char *inMethod, char *inURL,
                        char *inBody )
        : mError( false ), mURL( stringDuplicate( inURL ) ),
          mRequest( NULL ), mRequestPosition( -1 ),
          mResultReady( false ), mResult( NULL ),
          mSock( NULL ) {
        
    
    
    char *startString = "http://";

    char *urlCopy = stringDuplicate( inURL );

    
    char *urlStart = stringLocateIgnoreCase(  urlCopy, startString );

    char *serverStart;
    
    if( urlStart == NULL ) {
        // no http:// at start of URL
        serverStart = urlCopy;
        }
    else {
        serverStart = &( urlStart[ strlen( startString ) ] );
        }
    
    // find the first occurrence of "/", which is the end of the
    // server name

    char *serverNameCopy = stringDuplicate( serverStart );
        
    char *serverEnd = strstr( serverNameCopy, "/" );

    char *getPath = strstr( serverStart, "/" );

        
    if( serverEnd == NULL ) {
        serverEnd = &( serverStart[ strlen( serverStart ) ] );
        getPath = "/";
        }
    // terminate the url here to extract the server name
    serverEnd[0] = '\0';

    int portNumber = 80;

        // look for a port number
    char *colon = strstr( serverNameCopy, ":" );
    if( colon != NULL ) {
        char *portNumberString = &( colon[1] );
                
        int numRead = sscanf( portNumberString, "%d",
                              & portNumber );
        if( numRead != 1 ) {
            portNumber = 80;
            }

        // terminate the name here so port isn't taken as part
        // of the address
        colon[0] = '\0';
        }

    mSuppliedAddress = new HostAddress(
        stringDuplicate( serverNameCopy ),
        portNumber );

    mNumericalAddress = NULL;



    mNetworkUpThread = NULL;
    mLookupThread = NULL;
    

    if( ! isNetworkAlwaysOn() ) {
        // start thread to make sure it is on
        // (start name lookup thread later, after it is on)
        mNetworkUpThread = new BringNetworkUpThread( inURL );
        }
    else {
        // network always on
        // launch right into name lookup
        mLookupThread = new LookupThread( mSuppliedAddress );
        }
    

    mSock = NULL;
    
        
    // compose the request into a buffered stream
    StringBufferOutputStream tempStream;

    tempStream.writeString( inMethod );
    tempStream.writeString( " " );
    tempStream.writeString( getPath );
    tempStream.writeString( " HTTP/1.0\r\n" );
    tempStream.writeString( "Host: " );
    tempStream.writeString( serverNameCopy );
    tempStream.writeString( "\r\n" );
        
    if( inBody != NULL ) {
        char *lengthString = autoSprintf( "Content-Length: %d\r\n",
                                          strlen( inBody ) );
        tempStream.writeString( lengthString );
        delete [] lengthString;
        tempStream.writeString(
            "Content-Type: application/x-www-form-urlencoded\r\n\r\n" );
            
        tempStream.writeString( inBody );
        }
    else {
        tempStream.writeString( "\r\n" );
        }
        
    mRequest = tempStream.getString();
    mRequestPosition = 0;

        
        
    delete [] serverNameCopy;

    delete [] urlCopy;    
    }



WebRequest::~WebRequest() {

    // pass these to global thread destroyer, so we don't block here
    if( mNetworkUpThread != NULL ) {
        addThreadToDestroy( mNetworkUpThread );
        }

    if( mLookupThread != NULL ) {    
        addThreadToDestroy( mLookupThread );
        }
    
    delete mSuppliedAddress;
    
    if( mNumericalAddress != NULL ) {
        delete mNumericalAddress;
        }
    
    
    delete [] mURL;
    

    if( mSock != NULL ) {
        delete mSock;
        }
    
    if( mRequest != NULL ) {
        delete [] mRequest;
        }
    
    if( mResult != NULL ) {
        delete [] mResult;
        }
    }



int WebRequest::step() {
    if( mError ) {
        return -1;
        }

    if( mSock == NULL ) {
        

        // either mNetworkUpThread is NULL or mLookupThread is NULL,
        // but not both (lookup thread created when network up thread done)
        if( mNetworkUpThread != NULL ) {
            
            if( mNetworkUpThread->isNetworkCheckDone() ) {
                
                if( mNetworkUpThread->isNetworkUp() ) {
                    
                    // delete directly, because it is already finished
                    delete mNetworkUpThread;
                    
                    mNetworkUpThread = NULL;
                    
                    mLookupThread = new LookupThread( mSuppliedAddress );
                    }
                else {
                    // failed to bring network up
                    printf( "Error:  "
                            "WebRequest failed to bring network up.\n" );
                    
                    return -1;
                    }
                }
            else {
                // still bringing network up
                return 0;
                }
            }
        

        // we know mLookupThread is not NULL if we get here
        if( mLookupThread->isLookupDone() ) {
        

            mError = true;

            mNumericalAddress = mLookupThread->getResult();
            

            if( mNumericalAddress != NULL ) {
                

    
                // use timeout of 0 for non-blocking
                // will be set to true if we time out while connecting
                char timedOut;
                
                mSock = SocketClient::connectToServer( mNumericalAddress,
                                                       0,
                                                       &timedOut );
                
                if( mSock != NULL ) {
                    
                    mError = false;
                    }
                }

            if( mError ) {
                // lookup or socket construction failed
                
                if( mNumericalAddress == NULL ) {
                    printf( "Error:  "
                            "WebRequest failed to lookup %s\n",
                            mSuppliedAddress->mAddressString );
                    }
                else {
                    printf( "Error:  "
                            "WebRequest failed to construct "
                            "socket to %s:%d\n",
                            mNumericalAddress->mAddressString,
                            mNumericalAddress->mPort );
                    }
                
                return -1;
                }            
            }
        else {
            // still looking up
            return 0;
            }
        }
    

    int connectStatus = mSock->isConnected();
    
    if( connectStatus == 0 ) {
        // still trying to connect
        return 0;
        }
    else if( connectStatus < 0 ) {
        // failed to connect
        mError = true;
        
        printf( "Error:  "
                "WebRequest failed to connect to %s:%d\n",
                mNumericalAddress->mAddressString,
                mNumericalAddress->mPort );

        return -1;
        }
    else if( connectStatus == 1 ) {
        // connected
        
        if( mRequestPosition < (int)( strlen( mRequest ) ) ) {
            // try to send more
            char *remainingRequest = &( mRequest[ mRequestPosition ] );
            
            int numSent = mSock->send( (unsigned char *)remainingRequest,
                                       strlen( remainingRequest ),
                                       // non-blocking
                                       false );
            if( numSent == -1 ) {
                mError = true;
                
                printf( "Error:  "
                        "WebRequest failed to connect to "
                        "send full request\n" );

                return -1;
                }
            if( numSent == -2 ) {
                return 0;
                }
            
            mRequestPosition += numSent;
            

            // don't start looking for response in same step,
            // even if we just sent the entire request
            
            // in practice, it's never ready that fast
            return 0;
            }
        else if( mResultReady ) {
            return 1;
            }
        else {
            
            // done sending request
            // still receiving response
            
            long bufferLength = 5000;
            unsigned char *buffer = new unsigned char[ bufferLength ];

            // non-blocking

            // keep reading as long as we get full buffers
            int numRead = bufferLength;
            
            while( numRead > 0 ) {
                
                numRead = mSock->receive( buffer, bufferLength, 0 );
                
                if( numRead > 0 ) {
                    for( int i=0; i<numRead; i++ ) {
                        mResponse.push_back( buffer[i] );
                        }
                    }
                }
            
            
            delete [] buffer;
            

            if( numRead == -1 ) {
                // connection closed, done done receiving result

                // process it
                
                char *responseString = mResponse.getElementString();
                int responseLength = mResponse.size();
                
                if( stringLocateIgnoreCase( responseString, "404 Not Found" ) 
                    != NULL ) {
                    
                    mError = true;
                    delete [] responseString;

                    printf( "Error:  "
                            "WebRequest got 404 Not Found error for URL:  %s",
                            mURL );
                    
                    return -1;
                    }

                char *contentStartString = "\r\n\r\n";
                
                char *contentStart = strstr( responseString, 
                                             contentStartString );
            
                if( contentStart != NULL ) {
                    // skip start string
                    char *content =
                        &( contentStart[ strlen( contentStartString ) ] );


                    // pointer arithmetic:
                    // ugly, but we don't know that result does not contain
                    // \0, so we can't use streln to find result length
                    int resultLength =
                        responseLength
                        - strlen( contentStartString )
                        - (int)( contentStart - responseString );

                    mResult = new char[ resultLength + 1 ];
                    memcpy( mResult,
                            content, resultLength );

                    mResult[ resultLength ] = '\0';
                    mResultReady = true;
                    
                    delete [] responseString;
                    return 1;
                    }
                else {
                    mError = true;

                    printf( "Error:  "
                            "WebRequest got badly formatted response:\n%s\n",
                            responseString );

                    delete [] responseString;
                    
                    return -1;
                    }
                }
            else {
                // still receiving response
                return 0;
                }
            
            }
        }



    // should never get here
    // count it as error
    
    printf( "Error:  "
            "WebRequest got out of expected case tree\n" );

    return -1;
    }

        

char *WebRequest::getResult() {
    if( mResultReady ) {
        return stringDuplicate( mResult );
        }
    else {
        return NULL;
        }
    }