WebDNA Code Sample: Using cURL To Follow Redirected Location

Synopsis: When using TCPConnect in WebDNA, the location of the remote resource may be moved temporarily or permanently. This will result in WebDNA returning a connection error, as it will not follow the redirects returned in the http headers.

Solution: Create a function that uses cURL to test-flight the remote resource location. Curl has an option that is quite helpful in this situation. The -L flag instructs cURL to follow any redirect so that it reaches the eventual endpoint. The challenge is in returning some useful string to WebDNA, instead of http headers or the contents of the remote document. Again, cURL can easily do this using the -w option and the sub variable url_effective. The contents or headers, depending on whether we choose to have cURL GET the document or just check for its existence with HEAD, will be sent to /dev/null.

The Function

[function name=get_final_destination]
[text]full_result=[shell]curl -ILs -o /dev/null -w %{url_effective} [method_in]://[host_in][showif [port_in]!]:[port_in][/showif][path_in][/shell][/text]
[listwords words=[url][full_result][/url]&delimiters=:/]
	[showif [index]=1][text]method_part=[word][/text][/showif]
	[showif [index]=2][text]host_part=[word][/text][/showif]
	[showif [index]=3][text]port_part=[word][/text][/showif]	
[listwords words=[url][full_result][/url]&delimiters=/]
	[showif [index]>2][text]path_part=[path_part][delimiter][word][/text][/showif]
[hideif [url][full_result][/url]^[url][host_part]:[port_part][/url]]
[showif [url][port_part][/url]=]
	[text]port_part=[if "[method_part]"="https"][then]443[/then][else]80[/else][/if][/text]
[showif [url][path_part][/url]=][text]path_part=/[/text][/showif]


The function returns multiple value pairs, so we wrap the function in a multiple text variable context to pull the values into the current scope.

[text multi=t][get_final_destination method_in=http&host_in=www.webdna.us&port_in=&path_in=/][/text]

Feed the output variables to TCPConnect/TCPSend.

[tcpconnect host=[host_part]&port=[port_part][showif [url][method_part][/url]=https]&ssl=T[/showif]&timeout=5]
[TCPSend skipheader=T]GET [path_part] HTTP/1.1[UnURL]%0D%0A[/UnURL]*
Accept: text/html[UnURL]%0D%0A[/UnURL]*
Accept-Encoding: none[UnURL]%0D%0A[/UnURL]*
Accept-Language: en-us[UnURL]%0D%0A[/UnURL]*
Connection: close[UnURL]%0D%0A[/UnURL]*
Host: [host_part][UnURL]%0D%0A[/UnURL]*
User-Agent: Mozilla/5.0 ([product] [version])[UnURL]%0D%0A[/UnURL]*

Extra line feeds marked with * will need to be removed for functionality.  They are added here for readability.

Live Demonstration

Let cURL follow redirects, then feed TCPConnect/TCPSend the redirected location
--> http
--> www.webdna.us
--> /