Skip to content

Porting libgit2, problems with sockets #4902

Closed

Description

@vadimkantorov

I'm trying to port libgit2 to be able to do repo cloning and pushing from browser, having a credible git client in browser would be pretty neat.

Compilation went fine. First I tried to directly clone a GitHub repo by git protocol but it failed with WebSocket connection to 'ws://github.com/' failed: WebSocket is closed before the connection is established (Chrome console message; I could also see [SYN, SYN-ACK, ACK, PSH-ACK, ACK, FIN-ACK, ACK, FIN-ACK, ACK] sequence on Wireshark). I wondered if it's a problem with absence of HTTPS/SSH, and tried to build a native libgit2 without those protocols and clone something simpler. Native libgit2 clones the dash repo fine, but the assert of emscripten'ed one fails (testing code below): Error: failed to connect to git.kernel.org: Host is unreachable (error seems to be coming from https://github.com/libgit2/libgit2/blob/a6d833a29e100cae66d5144367e9102d093d4dbd/src/socket_stream.c#L124).

It's my first attempt at using emscripten and I don't know the debug/logging hooks yet. Should I try using https://kripken.github.io/emscripten-site/docs/api_reference/emscripten.h.html#socket-event-registration? Enabling -s SOCKET_DEBUG=1 printed only connect: ws://git.kernel.org:9418/, binary. Anything else?

What would be your thoughts?

[ -d libgit2 ] || git clone https://github.com/libgit2/libgit2

cd libgit2
[ -d build ] && rm -rf build
mkdir -p build && cd build

cat <<EOF > mytest.c
    #include <stdio.h>
    #include <git2.h>

    int main()
    {
        git_repository* repo = NULL;
        git_libgit2_init();
        if(0 != git_clone(&repo, "git://git.kernel.org/pub/scm/utils/dash/dash.git", "dash", NULL))
            printf("Error: %s\n", giterr_last()->message);
    }
EOF

function build_test_emscripten
{
    cmake .. -DCMAKE_SIZEOF_VOID_P=4 -DCMAKE_C_COMPILER="${EMSCRIPTEN_ROOT_PATH}/emcc" -DCMAKE_AR="${EMSCRIPTEN_ROOT_PATH}/emar" -DCMAKE_RANLIB="${EMSCRIPTEN_ROOT_PATH}/emranlib" -DCMAKE_C_FLAGS=$'-s EXPORTED_FUNCTIONS="[\'_git_clone\', \'_git_libgit2_init\',\'giterr_last\']" -O2' -DBUILD_CLAR=OFF -DUSE_SSH=OFF -DCURL=OFF -DUSE_OPENSSL=OFF
    MAKEFLAGS=8 cmake --build .
    "${EMSCRIPTEN_ROOT_PATH}/emcc" -s EXPORTED_FUNCTIONS="['_git_clone','_git_libgit2_init','_giterr_last']" -O2 -s LINKABLE=1 -o ../../libgit2.js libgit2.so
    "${EMSCRIPTEN_ROOT_PATH}/emcc" -o mytest.js mytest.c -I../include libgit2.so
    nodejs ./mytest.js
}

function build_test_native
{
    cmake .. -DCMAKE_C_FLAGS=$'-O2' -DBUILD_CLAR=OFF -DUSE_SSH=OFF -DCURL=OFF -DUSE_OPENSSL=OFF
    MAKEFLAGS=8 cmake --build .
    gcc -o mytest mytest.c -I../include -lgit2
    ./mytest
}

build_test_emscripten

Thanks!

UPD: My current understanding is that it can't work, because the Git servers don't support WebSockets as transport. Sorry for the long text :)

Activity

  1. CMCDragonkai commented on Aug 31, 2017

    @CMCDragonkai

    What do you lose by not compiling in openssl, libssh2 and curl?

  2. vadimkantorov commented on Aug 31, 2017

    @vadimkantorov
    Author

    I thought of first getting pure git HTTP protocol working

  3. petersalomonsen commented on Sep 13, 2017

    @petersalomonsen
    Contributor

    I solved this by bypassing the libgit http parser and just passing on data directly from the browser xhr. Created a new stream type in tls_stream.c that uses EM_ASM to create an XMLHttpRequest. The data from the xhr is already parsed so I removed the parser code in transports/http.c ( http_stream_read ) and passing data directly from the xhr stream:

    *(bytes_read) = git_stream_read(t->io, buffer, buf_size);

    Here's the changes in tls_stream.c - first of all connect the new stream type:

    
    int git_tls_stream_new(git_stream **out, const char *host, const char *port)
    {
    
    	if (tls_ctor)
    		return tls_ctor(out, host, port);
    
    #ifdef GIT_SECURE_TRANSPORT
    	return git_stransport_stream_new(out, host, port);
    #elif defined(GIT_OPENSSL)
    	return git_openssl_stream_new(out, host, port);
    #else
    	return git_open_emscripten_stream(out, host, port);
    	/*GIT_UNUSED(out);
    	GIT_UNUSED(host);
    	GIT_UNUSED(port);
    
    	giterr_set(GITERR_SSL, "there is no TLS stream available");
    	return -1;*/
    #endif
    }
    
    

    and then the stream functions:

    int emscripten_connect(git_stream *stream) {
    	printf("Connecting\n");	
    	return 1;
    }
    
    ssize_t emscripten_read(git_stream *stream, void *data, size_t len) {
    	size_t ret = 0;
    	
    	unsigned int readyState = 0;
    	EM_ASM_({		
    		setValue($0,window.gitxhr.readyState,"i32");
    	},&readyState);
    	
    	while(readyState!=4) {
    		EM_ASM_({
    			console.log("Waiting for data");
    			setValue($0,window.gitxhr.readyState,"i32");
    		},&readyState);
    		
    		emscripten_sleep(10);
    	}
    	
    	EM_ASM_({
    		if(window.gitxhr) {
    			var arrayBuffer = window.gitxhr.response; // Note: not oReq.responseText
    					
    			if (window.gitxhr.readyState===4 && arrayBuffer) {		
    				var availlen = (arrayBuffer.byteLength-window.gitxhrreadoffset);						
    				var len = availlen > $2 ? $2 : availlen;
    								
    				var byteArray = new Uint8Array(arrayBuffer,window.gitxhrreadoffset,len);		
    				console.log("read from ",arrayBuffer.byteLength,window.gitxhrreadoffset,len,byteArray[0]);
    				writeArrayToMemory(byteArray,$0);
    				setValue($1,len,"i32");
    				
    				window.gitxhrreadoffset+=len;				
    			}
    		} else {
    			setValue($1,-1,"i32");
    		}
    	},data,&ret,len);	
    	printf("Returning %d bytes, requested %d\n",ret,len);
    	return ret;
    }
    
    int emscripten_certificate(git_cert **out, git_stream *stream) {
    	printf("Checking certificate\n");
    	return 0;
    }
    
    ssize_t emscripten_write(git_stream *stream, const char *data, size_t len, int flags) {
    	EM_ASM_({
    		var data = Pointer_stringify($0);		
    		if(data.indexOf("GET ")===0) {				
    			window.gitxhr=new XMLHttpRequest();
    			window.gitxhrreadoffset = 0;
    			window.gitxhr.responseType = "arraybuffer";			
    			window.gitxhr.open("GET",data.split("\n")[0].split(" ")[1]);		
    			window.gitxhr.send();
    		} else if(data.indexOf("POST ")===0) {
    			window.gitxhr=new XMLHttpRequest();
    			window.gitxhrreadoffset = 0;
    			window.gitxhr.responseType = "arraybuffer";			
    			var requestlines = data.split("\n");			
    			window.gitxhr.open("POST",requestlines[0].split(" ")[1]);
    			
    			console.log(data);								
    			for(var n=1;n<requestlines.length;n++) {
    				if(requestlines[n].indexOf("Content-Type")===0) {
    					window.gitxhr.setRequestHeader("Content-Type",requestlines[n].split(": ")[1].trim());
    				}	
    			}
    			
    		} else {			
    			window.gitxhr.send(data);
    		}
    	},data);
    	
    	return len;
    }
    
    int emscripten_close(git_stream *stream) {
    	printf("Close\n");
    	return 0;
    }
    
    void emscripten_free(git_stream *stream) {
    	printf("Free\n");
    }
    
    int git_open_emscripten_stream(git_stream **out, const char *host, const char *port) {		
    	xhrstream.version = GIT_STREAM_VERSION;
    	xhrstream.connect = emscripten_connect;
    	xhrstream.read = emscripten_read;
    	xhrstream.write = emscripten_write;
    	xhrstream.close = emscripten_close;
    	xhrstream.free = emscripten_free;
    	xhrstream.certificate = emscripten_certificate;
    	xhrstream.encrypted = 1;
    	xhrstream.proxy_support = 0;
    
    	*out = &xhrstream;
    	printf("Stream setup \n");
    	return 0;
    }
    
    
  4. CMCDragonkai commented on Sep 13, 2017

    @CMCDragonkai

    @petersalomonsen Does your setup allow http cloning + https cloning? I always thought github had some cross origin constraint issue. What about ssh cloning?

    Also interesting way of passing pointers between EM_ASM and C/C++ code!

  5. vadimkantorov commented on Sep 13, 2017

    @vadimkantorov
    Author

    @petersalomonsen Wow, cool. Do I understand correctly that we still can't clone a repo from GitHub in browser context because of CORS and inability to do a HTTPS post to a foreign domain?

    Meanwhile I was implementing my own libgit transport relying on GitHub API, and while it would eventually work it has a lot of nasty details (and not very practical because of gazillion HTTP requests needed to fully clone a repo given that libgit doesn't support yet shallow repos libgit2/libgit2#4331).

    Also, xhrstream variable seems undeclared.

  6. petersalomonsen commented on Sep 13, 2017

    @petersalomonsen
    Contributor

    CORS prevents from cloning from github - so I had to use an Apache proxy (ProxyPass). Tested HTTPS cloning in the browser with same origin.

    SSH cloning not supported in the browser. When relying on browser XMLHttpRequest there is no support for SSH sockets.

    @vadimkantorov declaration: git_stream xhrstream;

    Attaching my modified files.
    http.c.txt
    tls_stream.c.txt

    The problem I'm facing with clone now is on "resolving deltas":

    net  66% (   0 kb,     6/    9)  /  idx  66% (    6/    9)  /  chk   0% (   0/   0) (null)
    libgit2.js:1 net  77% (   0 kb,     7/    9)  /  idx  77% (    7/    9)  /  chk   0% (   0/   0) (null)
    libgit2.js:1 net  88% (   0 kb,     8/    9)  /  idx  88% (    8/    9)  /  chk   0% (   0/   0) (null)
    libgit2.js:1 Resolving deltas 0/0
    libgit2.js:1 Resolving deltas 0/0
    
    

    ok up to here, but then I'm getting:

    failed to truncate pack file '/workdir/testrepo/.git/objects/pack/pack_git2_iJoMdK': Permission denied

    Which seems to be related to a filedescriptor on locked files after they've been saved and renambed (in indexer.c) . Still hacking into that.

  7. petersalomonsen commented on Sep 13, 2017

    @petersalomonsen
    Contributor

    @vadimkantorov @CMCDragonkai

    Successfully completed a git clone in the browser from https.

    The last problem I mentioned in the previous comment was solved by adding:

    fchmod(idx->pack->mwf.fd,0777);

    before

    /* Truncate file to undo rounding up to next page_size in append_to_pack */

    in the file indexer.c

    Screenshot is the output from the web console in chrome.

    gitcloneinthebrowser

  8. vadimkantorov commented on Sep 13, 2017

    @vadimkantorov
    Author

    Cool stuff :) In my understanding, the tsl_stream.c modifications can be sidestepped by calling git_stream_register_tls(git_open_emscripten_stream) before cloning. The only thing to be potentially upstreamed would be the http.c and indexer.c mods, right?

  9. petersalomonsen commented on Sep 14, 2017

    @petersalomonsen
    Contributor

    @vadimkantorov Yes, moving out the modifications in tls_stream.c and instead using git_stream_register_tls(git_open_emscripten_stream) would be cleaner.

    Also I would add a configuration option to bypass the http parser as I did in http.c. That one line changed in indexer.c shouldn't cause any problems to other platforms, so that could be upstreamed as is.

    So have to do some code cleanup after this hacking session, and would be good to either have emscripten build support in the original repository or a fork project here at github.

  10. CMCDragonkai commented on Sep 14, 2017

    @CMCDragonkai

    @petersalomonsen My preliminary google search found that people were able to compile libssh via emscripten. Not entirely sure if SSH works however, I suppose it should be using websockets in the browser, while in Node it should have an easier time.

    Could you expand on what you did with the Apache proxy, are you saying that you ran the proxy server-side, and made your xhr method proxy through it?

    On other gitjs implementations, some have investigated going through the actual Github OAuth API to do cloning.

  11. CMCDragonkai commented on Sep 14, 2017

    @CMCDragonkai

    @petersalomonsen Do you have a git repo/fork of your current progress?

  12. petersalomonsen commented on Sep 14, 2017

    @petersalomonsen
    Contributor

    @CMCDragonkai Yes the Apache proxy is on the serverside using ProxyPass directives, and the xhr method goes through it.

    About SSH you will run into the socket problem. As this thread started with I also faced that libgit2 tried to open a websocket - which is the default behavior of emscripten when trying to open a socket in the browser. I guess you could implement a websocket server that proxies to a tcp socket and make ssh work that way.

    Would be easier in node where you don't have the browser sandbox restrictions.

    I have a git repo, but have to clean it for passwords/hostnames before posting publicly.

  13. CMCDragonkai commented on Sep 14, 2017

    @CMCDragonkai

    @petersalomonsen Is the socket problem the same problem as CORS which requires a TCP proxy on server side, or is it a different socket problem where websockets can't handle libssh functionality?

  14. petersalomonsen commented on Sep 15, 2017

    @petersalomonsen
    Contributor

    @CMCDragonkai Only "guessing" here - but I think that emscripten makes libgit think it's dealing with a TCP socket while in reality it is a websocket. So I would believe it should work if you make a websocket server that forwards traffic to a tcp socket. Websocket still have to obey CORS just as XMLHttpRequest.

  15. petersalomonsen commented on Sep 19, 2017

    @petersalomonsen
    Contributor
  16. CMCDragonkai commented on Nov 8, 2017

    @CMCDragonkai

    I'm just looking at some of your commits, would it possible that they be pushed back to libgit2 upstream to make the original source more portable (to platforms like emscripten)?

  17. petersalomonsen commented on Nov 8, 2017

    @petersalomonsen
    Contributor

    Yes it would be very good to push it back to libgit2 upstream if they want it there. Probably need a better config option on disabling the HTTP parser but otherwise should be possible to integrate this. Do you see any other issues?

    Maybe best approach would be to start with registering an issue on libgit2 to start discussion on requirements for pushing back to upstream? @CMCDragonkai

  18. vadimkantorov commented on Nov 8, 2017

    @vadimkantorov
    Author

    There are those nasty pwrite and chmod, right? (I summarized your changes here, but it sparked no discussion)

  19. petersalomonsen commented on Nov 8, 2017

    @petersalomonsen
    Contributor

    Yes that's right. Those hacks for permissions (chmod) and mmap (pwrite) needs a better solution as they're redundant in other environments.

    I've upvoted your issue @vadimkantorov - but we need more votes ( @CMCDragonkai )

  20. CMCDragonkai commented on Nov 8, 2017

    @CMCDragonkai
    1. chmod in indexer.c, filebuf.c to explicitly give write permissions on the default read-only Emscripten's file system
    2. pwrite in indexer.c to explicitly give write permissions to a mmap which is also default read-only in Emscripten
    3. disabling http parsing of the response in transports/http.c
    4. disabling writing http headers in write_chunk in transports/http.c

    On my vfs that I'm integrating into emscripten, there won't be the problem of 1, because the vfs will be read/write by default. As for 2, there's an issue with mmap, for the existing library_memfs, mmap using MAP_SHARED is actually done only when the underlying buffer is the same as in HEAPU8, that means the files are already in the HEAPU8 buffer. And all mmap is doing is giving back a pointer to the subarray. There is an object call SYSCALLS.mappings that maintains a list of mappings to be synchronised using msync or munmap, however it does not work under the situations where files get resized. In all other cases the file's memory is just copied into a new allocation equivalent to MAP_PRIVATE.

    On my implementation of library_fs.js, MAP_SHARED is simply not possible without a full page table virtual memory management system. Because the files in VirtualFS (https://github.com/MatrixAI/js-virtualfs) are not stored in the same Emscripten heap, only MAP_PRIVATE is possible. So with regards to problem 3. it seems that the best course of action is just to disable MMAP. I can see that an emulated mmap is supplied if this constant is defined: https://github.com/libgit2/libgit2/search?q=NO_MMAP&type=Code&utf8=%E2%9C%93

  21. stale commented on Sep 19, 2019

    @stale

    This issue has been automatically marked as stale because there has been no activity in the past year. It will be closed automatically if no further activity occurs in the next 7 days. Feel free to re-open at any time if this issue is still relevant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions