Blob


1 #include <u.h>
2 #include <libc.h>
4 #undef accept
5 #undef announce
6 #undef dial
7 #undef setnetmtpt
8 #undef hangup
9 #undef listen
10 #undef netmkaddr
11 #undef reject
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <netinet/tcp.h>
16 #include <sys/un.h>
17 #include <netdb.h>
19 #undef unix
20 #define unix xunix
22 int
23 p9dial(char *addr, char *local, char *dummy2, int *dummy3)
24 {
25 char *buf;
26 char *net, *unix;
27 u32int host;
28 int port;
29 int proto;
30 socklen_t sn;
31 int n;
32 struct sockaddr_in sa, sal;
33 struct sockaddr_un su;
34 int s;
36 if(dummy2 || dummy3){
37 werrstr("cannot handle extra arguments in dial");
38 return -1;
39 }
41 buf = strdup(addr);
42 if(buf == nil)
43 return -1;
45 if(p9dialparse(buf, &net, &unix, &host, &port) < 0){
46 free(buf);
47 return -1;
48 }
50 if(strcmp(net, "tcp") == 0)
51 proto = SOCK_STREAM;
52 else if(strcmp(net, "udp") == 0)
53 proto = SOCK_DGRAM;
54 else if(strcmp(net, "unix") == 0)
55 goto Unix;
56 else{
57 werrstr("can only handle tcp, udp, and unix: not %s", net);
58 free(buf);
59 return -1;
60 }
61 free(buf);
63 memset(&sa, 0, sizeof sa);
64 memmove(&sa.sin_addr, &host, 4);
65 sa.sin_family = AF_INET;
66 sa.sin_port = htons(port);
67 if((s = socket(AF_INET, proto, 0)) < 0)
68 return -1;
70 if(local){
71 buf = strdup(local);
72 if(buf == nil){
73 close(s);
74 return -1;
75 }
76 if(p9dialparse(buf, &net, &unix, &host, &port) < 0){
77 badlocal:
78 free(buf);
79 close(s);
80 return -1;
81 }
82 if(unix){
83 werrstr("bad local address %s for dial %s", local, addr);
84 goto badlocal;
85 }
86 memset(&sal, 0, sizeof sal);
87 memmove(&sal.sin_addr, &local, 4);
88 sal.sin_family = AF_INET;
89 sal.sin_port = htons(port);
90 sn = sizeof n;
91 if(port && getsockopt(s, SOL_SOCKET, SO_TYPE, (void*)&n, &sn) >= 0
92 && n == SOCK_STREAM){
93 n = 1;
94 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&n, sizeof n);
95 }
96 if(bind(s, (struct sockaddr*)&sal, sizeof sal) < 0)
97 goto badlocal;
98 free(buf);
99 }
101 if(connect(s, (struct sockaddr*)&sa, sizeof sa) < 0){
102 close(s);
103 return -1;
105 if(proto == SOCK_STREAM){
106 int one = 1;
107 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char*)&one, sizeof one);
109 return s;
111 Unix:
112 if(local){
113 werrstr("local address not supported on unix network");
114 free(buf);
115 return -1;
117 memset(&su, 0, sizeof su);
118 su.sun_family = AF_UNIX;
119 if(strlen(unix)+1 > sizeof su.sun_path){
120 werrstr("unix socket name too long");
121 free(buf);
122 return -1;
124 strcpy(su.sun_path, unix);
125 free(buf);
126 if((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){
127 werrstr("socket: %r");
128 return -1;
130 if(connect(s, (struct sockaddr*)&su, sizeof su) < 0){
131 werrstr("connect %s: %r", su.sun_path);
132 close(s);
133 return -1;
135 return s;