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>
20 extern int _p9dialparse(char*, char**, char**, u32int*, int*);
21 #undef unix
23 int
24 p9dial(char *addr, char *dummy1, char *dummy2, int *dummy3)
25 {
26 char *buf;
27 char *net, *unix;
28 u32int host;
29 int port;
30 int proto;
31 struct sockaddr_in sa;
32 struct sockaddr_un su;
33 int s;
35 if(dummy1 || dummy2 || dummy3){
36 werrstr("cannot handle extra arguments in dial");
37 return -1;
38 }
40 buf = strdup(addr);
41 if(buf == nil)
42 return -1;
44 if(_p9dialparse(buf, &net, &unix, &host, &port) < 0){
45 free(buf);
46 return -1;
47 }
49 if(strcmp(net, "tcp") == 0)
50 proto = SOCK_STREAM;
51 else if(strcmp(net, "udp") == 0)
52 proto = SOCK_DGRAM;
53 else if(strcmp(net, "unix") == 0)
54 goto Unix;
55 else{
56 werrstr("can only handle tcp, udp, and unix: not %s", net);
57 free(buf);
58 return -1;
59 }
60 free(buf);
62 memset(&sa, 0, sizeof sa);
63 memmove(&sa.sin_addr, &host, 4);
64 sa.sin_family = AF_INET;
65 sa.sin_port = htons(port);
66 if((s = socket(AF_INET, proto, 0)) < 0)
67 return -1;
68 if(connect(s, (struct sockaddr*)&sa, sizeof sa) < 0){
69 close(s);
70 return -1;
71 }
72 if(proto == SOCK_STREAM){
73 int one = 1;
74 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char*)&one, sizeof one);
75 }
76 return s;
78 Unix:
79 memset(&su, 0, sizeof su);
80 su.sun_family = AF_UNIX;
81 if(strlen(unix)+1 > sizeof su.sun_path){
82 werrstr("unix socket name too long");
83 free(buf);
84 return -1;
85 }
86 strcpy(su.sun_path, unix);
87 free(buf);
88 if((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
89 return -1;
90 if(connect(s, (struct sockaddr*)&su, sizeof su) < 0){
91 close(s);
92 return -1;
93 }
94 return s;
95 }