41cb4c9bf30a53b48502d299e955f7230b470cfe
[jelmer/samba4-debian.git] / source / client / smbspool.c
1 /* 
2    Unix SMB/CIFS implementation.
3    SMB backend for the Common UNIX Printing System ("CUPS")
4    Copyright 1999 by Easy Software Products
5    Copyright Andrew Tridgell 1994-1998
6    Copyright Andrew Bartlett 2002
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24
25 /*
26  * Globals...
27  */
28
29 extern BOOL             in_client;      /* Boolean for client library */
30
31
32 /*
33  * Local functions...
34  */
35
36 static void             list_devices(void);
37 static struct smbcli_state      *smb_connect(const char *, const char *, const char *, const char *, const char *);
38 static int              smb_print(struct smbcli_state *, char *, FILE *);
39
40
41 /*
42  * 'main()' - Main entry for SMB backend.
43  */
44
45  int                            /* O - Exit status */
46  main(int  argc,                        /* I - Number of command-line arguments */
47      char *argv[])              /* I - Command-line arguments */
48 {
49   int           i;              /* Looping var */
50   int           copies;         /* Number of copies */
51   char          uri[1024],      /* URI */
52                 *sep,           /* Pointer to separator */
53                 *password;      /* Password */
54   const char    *username,      /* Username */
55                 *server,        /* Server name */
56                 *printer;       /* Printer name */
57   const char    *workgroup;     /* Workgroup */
58   FILE          *fp;            /* File to print */
59   int           status=0;               /* Status of LPD job */
60   struct smbcli_state *cli;     /* SMB interface */
61
62   /* we expect the URI in argv[0]. Detect the case where it is in argv[1] and cope */
63   if (argc > 2 && strncmp(argv[0],"smb://", 6) && !strncmp(argv[1],"smb://", 6)) {
64           argv++;
65           argc--;
66   }
67
68   if (argc == 1)
69   {
70    /*
71     * NEW!  In CUPS 1.1 the backends are run with no arguments to list the
72     *       available devices.  These can be devices served by this backend
73     *       or any other backends (i.e. you can have an SNMP backend that
74     *       is only used to enumerate the available network printers... :)
75     */
76
77     list_devices();
78     return (0);
79   }
80
81   if (argc < 6 || argc > 7)
82   {
83     fprintf(stderr, "Usage: %s [DEVICE_URI] job-id user title copies options [file]\n",
84             argv[0]);
85     fputs("       The DEVICE_URI environment variable can also contain the\n", stderr);
86     fputs("       destination printer:\n", stderr);
87     fputs("\n", stderr);
88     fputs("           smb://[username:password@][workgroup/]server/printer\n", stderr);
89     return (1);
90   }
91
92  /*
93   * If we have 7 arguments, print the file named on the command-line.
94   * Otherwise, print data from stdin...
95   */
96
97   if (argc == 6)
98   {
99    /*
100     * Print from Copy stdin to a temporary file...
101     */
102
103     fp     = stdin;
104     copies = 1;
105   }
106   else if ((fp = fopen(argv[6], "rb")) == NULL)
107   {
108     perror("ERROR: Unable to open print file");
109     return (1);
110   }
111   else
112     copies = atoi(argv[4]);
113
114  /*
115   * Find the URI...
116   */
117
118   if (strncmp(argv[0], "smb://", 6) == 0)
119     strncpy(uri, argv[0], sizeof(uri) - 1);
120   else if (getenv("DEVICE_URI") != NULL)
121     strncpy(uri, getenv("DEVICE_URI"), sizeof(uri) - 1);
122   else
123   {
124     fputs("ERROR: No device URI found in argv[0] or DEVICE_URI environment variable!\n", stderr);
125     return (1);
126   }
127
128   uri[sizeof(uri) - 1] = '\0';
129
130  /*
131   * Extract the destination from the URI...
132   */
133
134   if ((sep = strrchr_m(uri, '@')) != NULL)
135   {
136     username = uri + 6;
137     *sep++ = '\0';
138
139     server = sep;
140
141    /*
142     * Extract password as needed...
143     */
144
145     if ((password = strchr_m(username, ':')) != NULL)
146       *password++ = '\0';
147     else
148       password = "";
149   }
150   else
151   {
152     username = "";
153     password = "";
154     server   = uri + 6;
155   }
156
157   if ((sep = strchr_m(server, '/')) == NULL)
158   {
159     fputs("ERROR: Bad URI - need printer name!\n", stderr);
160     return (1);
161   }
162
163   *sep++ = '\0';
164   printer = sep;
165
166   if ((sep = strchr_m(printer, '/')) != NULL)
167   {
168    /*
169     * Convert to smb://[username:password@]workgroup/server/printer...
170     */
171
172     *sep++ = '\0';
173
174     workgroup = server;
175     server    = printer;
176     printer   = sep;
177   }
178   else
179     workgroup = NULL;
180
181  /*
182   * Setup the SAMBA server state...
183   */
184
185   setup_logging("smbspool", DEBUG_STDOUT);
186
187   in_client = True;   /* Make sure that we tell lp_load we are */
188
189   if (!lp_load(dyn_CONFIGFILE))
190   {
191     fprintf(stderr, "ERROR: Can't load %s - run testparm to debug it\n", dyn_CONFIGFILE);
192     return (1);
193   }
194
195   if (workgroup == NULL)
196     workgroup = lp_workgroup();
197
198   load_interfaces();
199
200   do
201   {
202     if ((cli = smb_connect(workgroup, server, printer, username, password)) == NULL)
203     {
204       if (getenv("CLASS") == NULL)
205       {
206         fprintf(stderr, "ERROR: Unable to connect to SAMBA host, will retry in 60 seconds...");
207         sleep (60);
208       }
209       else
210       {
211         fprintf(stderr, "ERROR: Unable to connect to SAMBA host, trying next printer...");
212         return (1);
213       }
214     }
215   }
216   while (cli == NULL);
217
218  /*
219   * Now that we are connected to the server, ignore SIGTERM so that we
220   * can finish out any page data the driver sends (e.g. to eject the
221   * current page...  Only ignore SIGTERM if we are printing data from
222   * stdin (otherwise you can't cancel raw jobs...)
223   */
224
225   if (argc < 7)
226     CatchSignal(SIGTERM, SIG_IGN);
227
228  /*
229   * Queue the job...
230   */
231
232   for (i = 0; i < copies; i ++)
233     if ((status = smb_print(cli, argv[3] /* title */, fp)) != 0)
234       break;
235
236   smbcli_shutdown(cli);
237
238  /*
239   * Return the queue status...
240   */
241
242   return (status);
243 }
244
245
246 /*
247  * 'list_devices()' - List the available printers seen on the network...
248  */
249
250 static void
251 list_devices(void)
252 {
253  /*
254   * Eventually, search the local workgroup for available hosts and printers.
255   */
256
257   puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
258 }
259
260
261 /*
262  * 'smb_connect()' - Return a connection to a server.
263  */
264
265 static struct smbcli_state *            /* O - SMB connection */
266 smb_connect(const char *workgroup,              /* I - Workgroup */
267             const char *server,         /* I - Server */
268             const char *share,          /* I - Printer */
269             const char *username,               /* I - Username */
270             const char *password)               /* I - Password */
271 {
272   struct smbcli_state   *c;             /* New connection */
273   char *myname;         /* Client name */
274   NTSTATUS nt_status;
275
276  /*
277   * Get the names and addresses of the client and server...
278   */
279
280   myname = get_myname();  
281         
282   nt_status = smbcli_full_connection(NULL, &c, myname, server, 0, share, NULL,
283                                      username, workgroup, password);
284   
285   free(myname);
286   if (!NT_STATUS_IS_OK(nt_status)) {
287           fprintf(stderr, "ERROR:  Connection failed with error %s\n", nt_errstr(nt_status));
288           return NULL;
289   }
290
291   /*
292    * Return the new connection...
293    */
294   
295   return (c);
296 }
297
298
299 /*
300  * 'smb_print()' - Queue a job for printing using the SMB protocol.
301  */
302
303 static int                              /* O - 0 = success, non-0 = failure */
304 smb_print(struct smbcli_state *cli,     /* I - SMB connection */
305           char             *title,      /* I - Title/job name */
306           FILE             *fp)         /* I - File to print */
307 {
308   int   fnum;           /* File number */
309   int   nbytes,         /* Number of bytes read */
310         tbytes;         /* Total bytes read */
311   char  buffer[8192],   /* Buffer for copy */
312         *ptr;           /* Pointer into tile */
313
314
315  /*
316   * Sanitize the title...
317   */
318
319   for (ptr = title; *ptr; ptr ++)
320     if (!isalnum((int)*ptr) && !isspace((int)*ptr))
321       *ptr = '_';
322
323  /*
324   * Open the printer device...
325   */
326
327   if ((fnum = smbcli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE)) == -1)
328   {
329     fprintf(stderr, "ERROR: %s opening remote file %s\n",
330             smbcli_errstr(cli), title);
331     return (1);
332   }
333
334  /*
335   * Copy the file to the printer...
336   */
337
338   if (fp != stdin)
339     rewind(fp);
340
341   tbytes = 0;
342
343   while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0)
344   {
345     if (smbcli_write(cli, fnum, 0, buffer, tbytes, nbytes) != nbytes)
346     {
347       fprintf(stderr, "ERROR: Error writing file: %s\n", smbcli_errstr(cli));
348       break;
349     }
350
351     tbytes += nbytes;
352   } 
353
354   if (!smbcli_close(cli, fnum))
355   {
356     fprintf(stderr, "ERROR: %s closing remote file %s\n",
357             smbcli_errstr(cli), title);
358     return (1);
359   }
360   else
361     return (0);
362 }